且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何知道用户是否在Android活动之外连续两次按了电源键?

更新时间:2023-12-02 23:53:58

您不能覆盖应用程序中的电源按钮.但是,当您按下电源按钮时,屏幕会打开/关闭.因此您可以使用广播接收器检测到这一点

You cannot override the power button press from your application. But when you press power button the screen turns on/off. So you can detect this using a broadcast receiver

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

和广播接收器类

public class MyBroadCastReciever extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            //Take count of the screen off position
        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            //Take count of the screen on position
        }
    }
}

希望这对您有所帮助.