3

Can the a backbutton press be detected from a service?

As the header says really? I have done a lot of googling but can't find a definitive answer. Nor a way to do it?

Bex
  • 4,898
  • 11
  • 50
  • 87

3 Answers3

4

Can the a backbutton press be detected from a service?

No, sorry. If you have an activity in the foreground, the activity can detect a BACK press. If you do not have an activity in the foreground, the BACK button has nothing to do with your code.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • 4
    I don't think this is entirely correct. The Service, for example, could execute code that shows a Window using `WindowManager#addView()`, and if that Window gains focus, the `KeyEvent.KEYCODE_BACK` event will be delivered to the root view of the window, I assume? It all depends on which window currently has focus... not the type of component you are using. Of course, 99% of the time your service will not be showing its own windows to the screen (unless you are re-writing Facebook Chatheads), so services in general won't be able to receive back-button click events. – Alex Lockwood Jul 28 '13 at 00:39
  • 1
    I am doing some chathead service demo. How I can add a listener to the window? I try it with `setonkeylistener` on a view but i can't catch de back action... :s – DaniG Jun 12 '17 at 20:10
2

Don't think so. Back button is something managed at activity level, while a service is totally separated from this level.

The only way you have is to communicate a back pression from your activity to your service. But, you need that your activity is in foreground.

Rainbowbreeze
  • 1,503
  • 1
  • 9
  • 14
0

If through your service your are adding view or something then you can use EditText box to capture back press. Just set its onKeyListerner. (Hide edittext box behind other view)

editText.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                Log.d("TAG", "onKey() called with: " + "v = [" + v + "], keyCode = [" + keyCode + "], event = [" + event + "]");
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction()== KeyEvent.ACTION_UP){
                    onBackPress();
                }
                return false;
            }
        });
Vivek Bansal
  • 1,301
  • 13
  • 21