我正在开发一个应用程序,我需要在按下电源按钮时执行 *** 作,但不幸的是,当按下电源按钮时我无法按下电源按钮的动作.我尝试使用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);}
和
@OverrIDepublic 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);}
解决方法:
我找到了答案,这可以通过使用带有PowerManager的AlarmManager来完成
@OverrIDepublic 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.
以上是内存溢出为你收集整理的覆盖Android中的电源按钮全部内容,希望文章能够帮你解决覆盖Android中的电源按钮所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)