Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Service with Overlay - catch back button press

How can i do that?

Current solution

I launch a transparent activity, that catches the back press, forwards it to my service and closes itself afterwards. But this activity will be visible in the current running activities and therefore it's not a very beautiful solution.

Solutions seen

I've seen an app that does catch the back press in a service - without an activity that catches the back press. If I show the current running activities, there is nothing from this app.

Question

How can this be done? I've read so many threads that say, this is not possible, but I can see, that there are apps that achieve that somehow...

like image 836
prom85 Avatar asked Jul 16 '15 18:07

prom85


People also ask

Do all Android devices have back button?

All Android devices provide a Back button for this type of navigation, so you should not add a Back button to your app's UI. Depending on the user's Android device, this button might be a physical button or a software button.

How to handle hardware back button in Android?

The hardware back button is found on most Android devices. In native applications it can be used to close modals, navigate to the previous view, exit an app, and more. By default in Ionic, when the back button is pressed, the current view will be popped off the navigation stack, and the previous view will be displayed.

How can I tell if my Android back button is pressed?

In order to check when the 'BACK' button is pressed, use onBackPressed() method from the Android library. Next, perform a check to see if the 'BACK' button is pressed again within 2 seconds and will close the app if it is so.


1 Answers

If you have an overlay window attached in a WindowManager in your service, put your view the attribute setFocusableInTouchMode(true), and put a key listener. You'll receive key events, like in this example:

view.setFocusableInTouchMode(true);
view.setOnKeyListener(new View.OnKeyListener() {
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK) {
            stopSelf();
            return true;
        }
        return false;
    }
});

Edited, I didn't use good stackoverflow account

like image 140
Philippe Mignard Avatar answered Oct 20 '22 04:10

Philippe Mignard