我正在开发一个应用程序,在其中按下电源按钮时我需要执行操作,但是不幸的是,在按下电源按钮时,我无法进行操作。我尝试使用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);
}




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

最佳答案

我找到了答案,可以通过将AlarmManager与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();
}



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

08-17 21:37