How to capture key events inside a service?

后端 未结 5 1989
天命终不由人
天命终不由人 2021-01-05 12:51

I want to be able to capture key events inside a service I am writing. I can do this inside an activity without problems, but all my attemps to get this working in a service

5条回答
  •  囚心锁ツ
    2021-01-05 13:15

    You can capture hardware key button events by using accessibility service, only you need to enable the service by going to accessibility settings after installing the app. Here is the code

        public class AccessiblityService extends AccessibilityService {
    
            @Override
            protected void onServiceConnected() {
                super.onServiceConnected();
                Log.d(TAG, "service is connected");
            }
    
            @Override
            public void onAccessibilityEvent(AccessibilityEvent accessibilityEvent) {
    
                Log.d(TAG, "onAccessibiltyEvent" + accessibilityEvent.toString());
    
            }
    
            @Override
            public void onInterrupt() {
    
            }
        // here you can intercept the keyevent
            @Override
            protected boolean onKeyEvent(KeyEvent event) {
                return handleKeyEvent(event);
            }
    
             private boolean handleKeyEvent(KeyEvent event) {
                int action = event.getAction();
                int keyCode = event.getKeyCode();
                if (action == KeyEvent.ACTION_DOWN) {
                    switch (keyCode) {
                        case KeyEvent.KEYCODE_VOLUME_DOWN:
                            //do something
                            return true;
    
                        case KeyEvent.KEYCODE_VOLUME_UP: {
                            //do something
                            return true;
                        }
                    }
                }
                return false;
            }
    
    } 
    

    manifest.xml

    
    
    
        
            
                
                    
                
                
            
            
                
                    
    
                    
                
                         
        
    
    
    

    accessibility_service.xml //create it in "xml" directory

    
    
    

提交回复
热议问题