【问题标题】:Want to Access Power Button events in android想要在android中访问电源按钮事件
【发布时间】:2016-05-11 09:08:49
【问题描述】:
   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 键,但不适用于电源/锁定按钮。为什么会发生这种情况? 建议一些示例或代码。

【问题讨论】:

标签: android android-event


【解决方案1】:

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

<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

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
    }
}
}

希望这对你有帮助。

注意:-为了让我的广播接收器始终在后台运行。我编写了一个后台服务,它不断在后台启动并增强我的广播接收器。

【讨论】:

  • 但是广播接收器不在后台运行意味着它在应用程序在前台或任务管理器中运行时如何处理这种情况?
【解决方案2】:

您应该在清单文件中添加以下权限:

&lt;uses-permission android:name="android.permission.PREVENT_POWER_KEY" /&gt;

【讨论】:

  • 此权限不再可用。最好遵循@Devendra Singh 的回答
猜你喜欢
  • 2011-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多