I am developing an application where I could listen to POWER_BUTTON clicked for 3 times consecutively in 3-5 seconds.
I have searched all the StackOverflow for answers but none of them has worked for me.
This answer from Lars D which should work on the activity doesn't work too though it is accepted.
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
Intent i = new Intent(this, ActivitySetupMenu.class);
startActivity(i);
return true;
}
return super.dispatchKeyEvent(event);
}
There is an app that is intending to do this, I installed it but still, it doesn't work maybe the API they used are depreciated or even has been removed.
The Reasons why these solutions do not work :
- when the App gets killed/destroyed and it no longer detects.
- The screen is locked and again it no longer detects.
- Maybe the SDK does not support it.
Maybe we can find a way to do it on the activity but I want to listen to the actions using a service/broadcast Receiver while the app is killed/in the background/when screen locked/ when screen off.
Well, this question is definitely repeated many times on StackOverflow but no complete or working answer has been given.
Since nobody tried to solve the question or maybe couldn't even understand the question, fortunately after many hours of searching the web I found this awesome website that solves exactly my problem and wanted to post it here too.
Problems which are solved now :
I am just writing down the steps in case the link may not work or be removed in future:
1.First we will create a broadcast receiver which can listen and process android screen on / off broadcast event as below.
ScreenOnOffReceiver.java
2. Register And Unregister ScreenOnOffReceiver In Activity.
Now we will create an activity and register ScreenOnOffReceiver in it’s onCreate() method, and unregister the receiver in it’s onDestroy() method as below.
ScreenOnOffActivity.java
Run Above Activity In Below Steps.
3. Register And Unregister Broadcast Receiver In Android Background Service
When you register the broadcast receiver in activity, it will be stopped after the activity exit.
To resolve this problem, we will create an android service object, and register and unregister the broadcast receiver in the service object.
Because the android service object will still run at the background after the activity exit, so the broadcast receiver will still run also after the android app exit.
3.1 Create Android Service Class.
3.1.1 Create A Java Class That Extends android.app.Service.
ScreenOnOffBackgroundService.java
3.1.2 Add Service Xml Tag In AndroidManifest.xml File.
3.1.3 Change Activity Java Code To Below.
Please notice the java code that start the service object.
ScreenOnOffActivity.java
Run the example again, you can see below picture. From the logcat output, we can see the broadcast receiver still running after the android app exit.