Search code examples
androidandroid-viewandroid-event

Touching a view that's always on screen


I have a view that's always on the screen (over other apps), I wan't to receive touch events and than to pass them farther.

The code from the running Service :

    WindowManager.LayoutParams localLayoutParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
            WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,  
            PixelFormat.TRANSLUCENT);

    v.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            Toast.makeText(getApplicationContext(), "view touched", Toast.LENGTH_SHORT).show();
            return false;
        }
    });

    WindowManager localWindowManager = (WindowManager)getSystemService("window");
    localWindowManager.addView(v, localLayoutParams);

currently I don't get the touches.


Solution

  • You want to declare your view as TYPE_SYSTEM_ALERT, as below:

    WindowManager.LayoutParams params =
            new WindowManager.LayoutParams(width, height, x, y,
                    WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                            | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
                    PixelFormat.TRANSLUCENT);
    params.gravity = Gravity.LEFT | Gravity.TOP;
    

    This way it will only respond to touches on the view itself.

    This code comes from a working task-switcher that I designed. I did not use FLAG_WATCH_OUTSIDE_TOUCH as it caused problems for me when interacting with other windows below my overlay.


    As far as passing the touches on to other apps - that is no longer possible, as it represents a security risk.

    I recently put a few more details together on a similar question, which you might find interesting to read:

    Also an interesting library mentioned by Edward Jezisek is StandOut by pingpongboss:

    Since it is open source, you can go through the code to figure out what he is doing.