How I can receive hardware key events in sleep mod

2020-07-17 08:00发布

问题:

I'm writing an application that allows people in danger to call 911.

This is how it should work:

  1. He (or she) feels danger.
  2. He pushes the volume-down key three times.
  3. My app calls 911.

But I'm facing the following problem: how can I receive a hardward key event in sleep mode?

I've searched Google and other search engines, but can't find anything related.

回答1:

public class YourBoardcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
                if (Intent.ACTION_CAMERA_BUTTON.equals(intent.getAction())) {
                        Intent main = new Intent();// 
                }
        }
}

And in your Manifest :

<receiver android:name="YourBoardcastReceiver">
                <intent-filter>
                        <action android:name="android.intent.action.SCREEN_ON" />
                </intent-filter>
</receiver>


回答2:

The only way I think you could do that is with a BroadcastReceiver, but it seems that the volume buttons do not generate an Intent when the screen is off (see here). The closest thing you might be able to do is use the camera button to do something similar.

Perhaps it is better this way, anyway, though. I imagine it would annoy users if their phone called 911 while in their pocket because of the volume buttons, or the camera button too for that matter. Also, it's not something I would expect to happen.