Search code examples
androidandroid-screen-supportandroid-wake-lockandroid-screenandroid-powermanager

Android power button override and disable while application runing


hi i need to keep the device screen on mood, while application running. disable the power button functionality to off the screen. I have tried following codes

getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);

and wake locks

@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();  
    }

Thanks in advance


Solution

  • This is not possible, for security reasons. HOME and POWER buttons are two things you will not be able to directly override without system-grade permissions. After all, the user wouldn't like your app to take control of their device, would they? ;-)

    You should plan the functionality in such a way that a wakelock or

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    

    is enough :-)

    EDIT:

    There are tutorials such as the one uday linked, but the effects are generally unreliable and work only on some devices. I have developed an app like that and trust me, you do not want to have to debug this ;-)