Привет всем, кого я знаю, другие пытались сделать что-то похожее, но все, что я могу найти, это старое и, кажется, не работает для меня на Android 10.
То, что я хочу сделать, это на самом деле оверлей, который немного напоминает функцию «Показать статистику ЦП» в некоторых пользовательских настройках ПЗУ. Вот что я имею в виду:
.
У меня есть приложение для ядра, и я хочу показать наложение вроде этого, показывающее статистику ядра, такую как cpu и gpu freqs. Код для частоты процессора и графического процессора не является проблемой.
Я действительно хочу знать, как создать оверлей. Вот то, что я пробовал так далеко от учебников, которые я нашел в Интернете, но каждый учебник, который я пробую, выдает ту же ошибку: Unable to add window -- token null is not valid; is your activity running?
Вот что я использую в манифесте. xml:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<application>...
...
...
<service android:name="org.pierre2324.nogravity.HUD"/>
</application>
Вот мой фрагмент, который содержит переключатель для включения службы наложения (HUD):
public class MainFragment9 extends Fragment {
private static final String TAG = "MainFragment9";
private Switch overandroidlaySwitch;
@Nullable
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.main_fragment9, container, false);
overlaySwitch = (Switch) view.findViewById(R.id.overlay_toggle);
//region HUD SWITCH
overlaySwitch.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if (overlaySwitch.isChecked()) {
//Start the service
if(!isSystemAlertPermissionGranted(MainFragment9.this.getActivity())){
requestSystemAlertPermission(MainFragment9.this.getActivity(),1);
}
if (Build.VERSION.SDK_INT >= 26) {
MainFragment9.this.getActivity().getApplicationContext().startForegroundService(new Intent(MainFragment9.this.getActivity().getApplicationContext(), HUD.class));
} else {
MainFragment9.this.getActivity().startService(new Intent(MainFragment9.this.getActivity().getApplicationContext(), HUD.class));
}
newEditor.putBoolean("Overlay", true);
Toast.makeText(MainFragment9.this.getActivity() ,"NGK Overlay enabled!", Toast.LENGTH_SHORT).show();
} else {
//Stop the service
MainFragment9.this.getContext().stopService(new Intent(getContext(), HUD.class));
newEditor.putBoolean("Overlay", false);
Toast.makeText(MainFragment9.this.getContext(), "NGK Overlay disabled", Toast.LENGTH_SHORT).show();
}
newEditor.apply();
}
});
//endregion
return view;
}
}
И, наконец, вот мой сервис HUD:
public class HUD extends Service{
private View topLeftView;
private Button overlayedButton;
private WindowManager wm;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
topLeftView = new View(this);
WindowManager.LayoutParams topLeftParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_TOAST, WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, PixelFormat.TRANSLUCENT);
topLeftParams.gravity = Gravity.LEFT | Gravity.TOP;
topLeftParams.x = 0;
topLeftParams.y = 0;
topLeftParams.width = 0;
topLeftParams.height = 0;
wm.addView(topLeftView, topLeftParams); //Crashes here...
}
@Override
public void onDestroy() {
super.onDestroy();
if (overlayedButton != null) {
wm.removeView(overlayedButton);
wm.removeView(topLeftView);
overlayedButton = null;
topLeftView = null;
}
}
}
Еще раз спасибо за вашу помощь!
РЕДАКТИРОВАТЬ:
Я получил оверлей для работы, используя отдельный файл xml для самого оверлея и со следующим кодом:
public class HUD extends Service{
static final String CHANNEL_ID = "Overlay_notification_channel";
private static final int LayoutParamFlags = WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
private LayoutInflater inflater;
private Display mDisplay;
private View layoutView;
private WindowManager windowManager;
private WindowManager.LayoutParams params;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
LayoutParamFlags,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.END;
windowManager = (WindowManager) this.getSystemService(WINDOW_SERVICE);
mDisplay = windowManager.getDefaultDisplay();
inflater = LayoutInflater.from(this);
layoutView = inflater.inflate(R.layout.ngk_overlay, null);
windowManager.addView(layoutView, params);
//This is needed to keep the service running in background just needs a notification to call with startForeground();
if (Build.VERSION.SDK_INT >= 26) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, getString(R.string.ngk_overlay_notification), NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setSound(null, null);
notificationManager.createNotificationChannel(notificationChannel);
Notification.Builder builder = new Notification.Builder(this, CHANNEL_ID);
builder.setContentTitle(getString(R.string.ngk_overlay)).setContentText(getString(R.string.ngk_overlay_notification)).setSmallIcon(R.drawable.ic_mono2);
startForeground(1, builder.build());
}
}
@Override
public void onDestroy() {
super.onDestroy();
windowManager.removeView(layoutView);
}
}