覆盖Android中的电源按钮

Bob*_*Bob 1 android

我正在开发一个应用程序,我需要在按下电源按钮时执行操作,但不幸的是,当按下电源按钮时,我无法处理电源按钮的动作.我尝试使用onKeyDown()和dispatchKeyEvent()方法,但似乎没有任何工作.谁能建议我解决这个问题的任何其他方法或解决方案.

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);
}
Run Code Online (Sandbox Code Playgroud)

@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);
}
Run Code Online (Sandbox Code Playgroud)

Bob*_*Bob 7

我找到了答案,这可以通过使用带有PowerManager的AlarmManager来完成

@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();  
}
Run Code Online (Sandbox Code Playgroud)

首先屏幕熄灭然后我使用AlarmManager唤醒它.我无法通过覆盖电源按钮控件来停止屏幕进入关闭状态.我只是在设备进入睡眠状态后立即唤醒它.