如何知道用户是否在Android活动之外连续两次按了电源键? [英] How to know if the user has pressed power key twice or thrice continuously outside the activity in android?
问题描述
我需要知道用户何时连续按下电源键2或3次. 但是,如果用户不在应用程序中,可以在主屏幕上说,甚至使用任何其他应用程序.
I need to know when the user will press the power key continuously 2 or 3 times. But in the case the user is out of the application lets say on the home screen or even using any other application.
我在活动上获得了电源键的侦听器事件,但在服务上却没有.
I getting the listener event of the power key on the activity but not on the service.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(KeyEvent.KEYCODE_POWER == event.getKeyCode()){
Log.e("POWER", "pow");
return true;//If event is handled, falseif
}
return super.onKeyDown(keyCode, event);
}
我怎么知道用户是否在活动之外按下了电源按钮?
How can i know if the user has pressed the power button outside the activity?
推荐答案
您不能覆盖应用程序中的电源按钮.但是,当您按下电源按钮时,屏幕会打开/关闭.因此您可以使用广播接收器检测到这一点
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
}
}
}
希望这对您有所帮助.
这篇关于如何知道用户是否在Android活动之外连续两次按了电源键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!