Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a floating view to Android Window manager and listen to System/Hardware back button events

I have a service which displays a floating view on the window manager (using WINDOW_TYPE_ALERT permission). I'm able to display it and perform actions. But, I have two specific questions:

  1. Regarding the implementation of the floating view
  2. How to listen to system back button event so that I can dismiss the view.

Implementation:

In the manifest I added permissions for:

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

I have a broadcast receiver which will listen for Alarm events. Upon receiving the event, I'm starting a service to display the floating view. The following is the code I'm using to create the view.

LayoutParams layOutParams = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
                WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
                PixelFormat.TRANSLUCENT);

Whenever a user performs any action on the view, I'm removing the view from window manager and killing the service.

What I would like to know is - if this is the right way to approach the problem or are there any better ways to do it? And, should I make changes to the LayoutParams or keep them as is?

Secondly, I would also like to dismiss this floating view when there is SYSTEM BACK/HARDWARE BACK button press event. Any pointers on how to do this would be helpful.

Attaching a screenshot of the floating view for better understanding:

Floating View

like image 710
Handroid Avatar asked Aug 08 '13 10:08

Handroid


2 Answers

In terms of back button detection - I made it to work in a following way (everything happens in service onCreate code):

  1. Wrap your desired view into ViewGroup (LinearLayout, Relative or other)
  2. override dispatchKeyEvent like this in wrapper view:

mView = new RelativeLayout(this) {
        @Override
        public boolean dispatchKeyEvent(KeyEvent event) {
            if (event.getKeyCode()==KeyEvent.KEYCODE_BACK) {
                // < your action >
                return true;
            }
            return super.dispatchKeyEvent(event);
        }
};
  1. add wrapper view to the window manager, and be sure that WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE is not set on wrapper layout params.
like image 151
qbasso Avatar answered Nov 15 '22 18:11

qbasso


Have a look at Standout Library , which is good for handling floating windows , it seems it is also not handling back press event , contacting developer might help.

And one more way is you can try opening activity with semi transparent background/theme to get the similar effect used in floating window in Any.do and backpress event can be handled

like image 40
Balaji Avatar answered Nov 15 '22 19:11

Balaji