想要访问Android中的电源按钮事件 [英] Want to Access Power Button events in android
问题描述
i=0;
public boolean onKeyDown(int keyCode, KeyEvent event) {
System.out.println("In Key Down Method." + event.getKeyCode());
if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
i++;
System.out.println("Power button pressed.");
if (i == 2) {
System.out.println("Power button pressed continuoulsy 3 times.");
Toast.makeText(MainActivity.this, "Power button pressed " + i + " times.", Toast.LENGTH_SHORT).show();
} else {
System.out.println("Power button pressed continuoulsy " + i + " times.");
Toast.makeText(MainActivity.this, "Power button pressed " + i + " times.", Toast.LENGTH_SHORT).show();
}
}
return super.onKeyDown(keyCode, event);
}
我正在尝试使用上述代码访问电源按钮事件。 Volume_Up和Volume_Down键,但不能用于电源/锁定按钮。为什么会发生这种情况?
建议一些示例或代码。
I am trying to access power button event using above code.Its working fine for Volume_Up and Volume_Down Key but not Working For Power/Lock Button.Why it happens? Suggest Some Example or code.
推荐答案
您不能覆盖应用程序中的电源按钮。但是,当您按下电源按钮时,屏幕会打开/关闭。因此,您可以使用广播接收器检测到此情况。
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>
MyBroadCastReciever.java
MyBroadCastReciever.java
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
}
}
}
希望
注意:-为了使广播接收器始终在后台运行。我编写了一个后台服务,该服务不断在后台启动,并增强了我的广播接收器。
Note:-For to keep my broadcast receiver always running in Background.I am written one Background Service which continuously start in background and give boost to my broadcast receiver.
这篇关于想要访问Android中的电源按钮事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!