I\'m developing an app in which I need to do an action when the power button is pressed but unfortunately I cant handel the action of power button when it is pressed. I trie
I don't know what you intend to do, but you could use a BroadcastReceiver
and listen for the android.intent.action.SCREEN_OFF
or Intent.ACTION_SCREEN_OFF
which is sent when power button is pressed (and screen is on).
Unfortunately this intent will be sent when the screen times out too. But I think you can prevent the phone from being locked (while in an application) like this
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
I found the answer and this can be done by using the AlarmManager with the PowerManager
@Override
public void onReceive(Context context, Intent intent) {
if ((intent.getAction().equals(Intent.ACTION_SCREEN_OFF))) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "TEST");
wakeLock.acquire();
AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent inten = new Intent(context,NewActivity.class);
PendingIntent pi = PendingIntent.getActivity(context, 0, inten, 0);
alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 100, pi);
}
}
// Finish your WakeLock HERE. call this method after U put the activity in front or when u exit from the new activity.
public void finishWakeLocker(){
if (wakeLock != null)
wakeLock.release();
}
Here first the screen goes off and then I'm waking it by using the AlarmManager. I couldn't stop the screen going to off state by overriding the Power button controls. I'm just waking up the device as soon as it goes to sleep state.
Fortunately, this is not possible, except perhaps via custom firmware.