Overriding the power button in Android

后端 未结 3 2054
陌清茗
陌清茗 2020-12-01 17:40

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

3条回答
  •  一生所求
    2020-12-01 18:19

    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.

提交回复
热议问题