Search code examples
androidserviceback

Is there an onBackPressed() alternative for a service?


I know that services cannot implement Back key press and I understand the rationale. But there is an app called SideBar (on Play Store) that reacts to back key presses. It is a service that adds a view as system overlay and removes the view when the back key is pressed. Can anybody explain how this is done?

Here is another app that does it well. I have scoured the web, but have not found a solution to this problem. Any ideas?


Solution

  • Found the answer on another similar question here.

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