WindowManager cannot create a view and the application crashes after launch. I’m trying to make an image on top of all windows, but the WindowManager can’t add a view. Judging by the log, the application crashes after windowManager.addView
On MainActivity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("SuperShot", "started");
EdgeToEdge.enable(this);
floatingButton = findViewById(R.id.activate);
if (!Settings.canDrawOverlays(this)) {
Intent permissionService = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
startActivityForResult(permissionService, ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE);
}
Intent floatingButtonService = new Intent(this, FloatingButton.class);
startService(floatingButtonService);
}
On FloatingButton service:
@Override
public void onCreate() {
super.onCreate();
Log.i("SuperShot", "INTENT");
ImageView floatingButton = MainActivity.floatingButton;
Log.i("SuperShot", "button");
windowManager = (WindowManager)getSystemService(WINDOW_SERVICE);
Log.i("SuperShot", "WINDOW MANAGING");
final LayoutParams layoutParams = getLayoutParams();
windowManager.addView(floatingButton, layoutParams);
Log.i("SuperShot", "WINDOW MANAGED");
try {
OnTouchListener onTouchListener = getOnTouchListener(layoutParams);
floatingButton.setOnTouchListener(onTouchListener);
Log.i("SuperShot", "all good");
} catch (Exception exception) {
Log.e("SuperShot", exception.getMessage());
}
}
private LayoutParams getLayoutParams() {
Log.i("SuperShot", "layparams_start");
final LayoutParams layoutParams = new WindowManager.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT,
LayoutParams.TYPE_PHONE,
LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT
);
layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
layoutParams.x = 0;
layoutParams.y = 100;
Log.i("SuperShot", "layparams_end");
return layoutParams;
}
Help me understand what the problem is.