Service with Overlay - catch back button press

前端 未结 4 1349
生来不讨喜
生来不讨喜 2021-02-08 04:47

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 af

4条回答
  •  名媛妹妹
    2021-02-08 05:20

    You can catch the back button click event. For this you need to create container class of your OverlayView. For example: create class Overlay which will extends some ViewGroup class. Than, in the class, inflate your xml layout and add it to your Overlay.class ViewGroup. Than in Overlay.class override method dispatchKeyEvent(KeyEvent event). That's all!

    class Overlay extends FrameLayout{
      
      public Overlay(@NonNull Context context) {
            super(new ContextThemeWrapper(context, R.style.AppTheme));
    
            initView();
        }
        
        private void initView() {
          //inflate your xml here
          //than do: this.addView();
          //And in the end add your Overlay to WindowManager (in Service class of course).
        }
        
         @Override
        public boolean dispatchKeyEvent(KeyEvent event) {
            if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
                //do staff here
                // and return True!
                return true;
            }
            return super.dispatchKeyEvent(event);
        }
    }

提交回复
热议问题