How to create an overlay window to show over all apps on Android 10

北慕城南 提交于 2021-01-29 12:34:57

问题


Hi everyone I know others tried to do some similar things, but all I can find is old and doesn't seem to work for me on Android 10.

What I want to do is actually an overlay that looks a little bit like "Show CPU stats" feature in some custom ROMs dev-options. Here's what I mean:

.

I have a kernel app and I want to show an overlay like this showing kernel stats like cpu and gpu freqs. Code for cpu and gpu freqs is not a problem.

I actually want to know how to create an overlay. Here's what I tried so far from tutorials I found online, but every tutorial I try I get the same error: Unable to add window -- token null is not valid; is your activity running?

Here's what I use in manifest.xml:

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<application>...
...
...
    <service android:name="org.pierre2324.nogravity.HUD"/>
</application>

Here's my fragment which contains a toggle to enable the overlay (HUD) service:

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;
    }
}

And finally here's my HUD service:

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;
        }
    }
}

Thanks again for your help!

EDIT:

I got the overlay to work using a separate xml file for the overlay itself and with following code:

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);
    }
}

回答1:


Did you add the service to the manifest like this?

<service android:name="com.xxx.xxx.HUD">
</service>
</application>

Or maybe try WindowManager.LayoutParams.TYPE_PHONE (but i think thats just for older api's).

Edit: Also, try to get the context/activity different.

MainFragment9.this.getActivity().getApplicationContext() and MainFragment9.this.getActivity()

doesn't seem very good. Declare the Activity object outside of the methods. Something more like this (untested pseudo code):

...
private Switch overandroidlaySwitch;
private Activity myActivity;
    @Nullable
    public View onCreateView
    myActivity = getActivity();


来源:https://stackoverflow.com/questions/60454766/how-to-create-an-overlay-window-to-show-over-all-apps-on-android-10

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!