1
votes

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 tried using the onKeyDown() and dispatchKeyEvent() methods but nothing seems to be working. Can anyone suggest me any other method or solution for this problem.

public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
    // The action I want to perform when power button is pressed.
    return true;
}
return super.onKeyDown(keyCode, event);
}

and

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
    Intent i = new Intent(this, NewActivity.class);
    startActivity(i);
    return true;
}
return super.dispatchKeyEvent(event);
}
3
if you only worry about your own device and if it's rooted, you can modify the keyboard layout filestefan

3 Answers

8
votes

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.

2
votes

Fortunately, this is not possible, except perhaps via custom firmware.

0
votes

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);