John
John

Reputation: 6268

How to intercept the back button on an Android Service?

I'm displaying a layout over all the other apps with ApplicationOverlay and the WindowManager.

When I click the back button. The OnBackPressed() override of my activity doesn't fire because of the overlay.

How can I detect and cancel the back button from a Service on android so that when I press back I can make my application change its layout?

Upvotes: 1

Views: 522

Answers (2)

Leo Zhu
Leo Zhu

Reputation: 14956

When you create WindowManagerLayoutParams add the below flags:

layoutParams.Flags = WindowManagerFlags.NotTouchModal;
layoutParams.Flags = WindowManagerFlags.NotFocusable;

then you could fire the OnBackPressed() method in your activity.

Upvotes: 0

Kyito
Kyito

Reputation: 76

If you have the overlay attached to the WindowsManager, you just need to add a listener to the view:

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

Upvotes: 1

Related Questions