Creating a system overlay window (always on top)

前端 未结 16 944
南方客
南方客 2020-11-21 07:07

I\'m trying to create an always-op-top button/clickable-image which stays on top of all the windows all the time.

The proof of concept is

  • here - Smar
16条回答
  •  粉色の甜心
    2020-11-21 07:20

    This might be a stupid solution. But it works. If you can improve it, please let me know.

    OnCreate of your Service: I have used WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH flag. This is the only change in service.

    @Override
        public void onCreate() {
            super.onCreate();
            Toast.makeText(getBaseContext(),"onCreate", Toast.LENGTH_LONG).show();
            mView = new HUDView(this);
            WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                    WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
                    WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
                    PixelFormat.TRANSLUCENT);
            params.gravity = Gravity.RIGHT | Gravity.TOP;
            params.setTitle("Load Average");
            WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
            wm.addView(mView, params);
        }
    

    Now, you will start getting each and every click event. So, you need to rectify in your event handler.

    In your ViewGroup touch event

    @Override
    public boolean onTouchEvent(MotionEvent event) {
    
        // ATTENTION: GET THE X,Y OF EVENT FROM THE PARAMETER
        // THEN CHECK IF THAT IS INSIDE YOUR DESIRED AREA
    
    
        Toast.makeText(getContext(),"onTouchEvent", Toast.LENGTH_LONG).show();
        return true;
    }
    

    Also you may need to add this permission to your manifest:

    
    

提交回复
热议问题