4

I want to listen device power button in an android service. I can’t use key listener since I’m in a service. Currently I’m doing this by registering a broadcast listener with android.intent.action.SCREEN_OFF/android.intent.action.SCREEN_ON filter like below.

IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
Receiver mReceiver = new Receiver();
registerReceiver(mReceiver, filter);

Problem

This is not an ideal way to do this since screen status can change without pressing the power button. For an example, when ringing the phone for an in-coming call, it will on the screen. How can I listen exact hardware power button? Or is it not possible?

1 Answers1

-1

When device power button press then dispatchKeyEvent method call

     /* lock power button */
        @Override
        public boolean dispatchKeyEvent(@NonNull KeyEvent event)
        {
            return event.getKeyCode() == KeyEvent.KEYCODE_POWER || blockedKeys.contains(event.getKeyCode()) || super.dispatchKeyEvent(event);
        }
Komal12
  • 3,340
  • 4
  • 16
  • 25