Want to Access Power Button events in android

放肆的年华 提交于 2019-11-28 00:14:11
Devendra Singh

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

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

Hope this is helpful for you.

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.

You should add the following permission to your manifest file:

<uses-permission android:name="android.permission.PREVENT_POWER_KEY" />

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!