I want to capture Power button press event
in my app and that too inside a Service that runs in background. For this I used following code with Broadcast Receiver.
private static final String ACTION="android.intent.action.SCREEN_ON";
private BroadcastReceiver yourReceiver;
onReceive() Method:
final IntentFilter theFilter = new IntentFilter();
theFilter.addAction(ACTION);
this.yourReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Do whatever you need it to do when it receives the broadcast
// Example show a Toast message...
Log.d("button","button pressed");
Toast.makeText(context,"pressed",Toast.LENGTH_LONG).show();
}
};
With this code I am able to detect button's press event inside receiver.
Now I want to detect that whether power button was pressed for 3 or more seconds then I want to perform specific action inside my receiver. For this I found out this method
@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_POWER) {
// Do something here...
return true;
}
return super.onKeyLongPress(keyCode, event);
}
But I found out that this method will only run inside an activity, but I want to call it inside a Service.
Is there any way to detect whether power button was pressed for 3 seconds or can we use the above method inside Service.