Overriding the power button in Android

Solution 1:

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.

Solution 2:

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