android程序监听home键与电源键

来源:本站
导读:目前正在解读《android程序监听home键与电源键》的相关信息,《android程序监听home键与电源键》是由用户自行发布的知识型内容!下面请观看由(电工技术网 - www.9ddd.net)用户发布《android程序监听home键与电源键》的详细说明。
简介:android程序监听home键与电源键

01privatefinalBroadcastReceiverhomePressReceiver=newBroadcastReceiver(){02finalStringSYSTEM_DIALOG_REASON_KEY="reason";03finalStringSYSTEM_DIALOG_REASON_HOME_KEY="homekey";04@Override05publicvoidonReceive(Contextcontext,Intentintent){06Stringaction=intent.getAction();07if(action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)){08Stringreason=intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);09if(reason!=null&&reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)){10//自己随意控制程序,关闭...11}12}13}14};

然后在onreate()方法中,注册

1finalIntentFilterhomeFilter=newIntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);2registerReceiver(homePressReceiver,homeFilter);

当然最后为了程序的严谨性也是为了防止出错,我们在onDestory()方法中,也要解除注册

1if(homePressReceiver!=null){2try{3unregisterReceiver(homePressReceiver);4}catch(Exceptione){5Log.e(TAG,"unregisterReceiverhomePressReceiverfailure:"+e.getCause());6}7}

2,电源监听,先要有权限

1<uses-permissionandroid:name="android.permission.WAKE_LOCK"/>

然后监听两个action

01Intent.ACTION_SCREEN_OFF02Intent.ACTION_SCREEN_ON03privatefinalBroadcastReceivermBatInfoReceiver=newBroadcastReceiver(){04@Override05publicvoidonReceive(finalContextcontext,finalIntentintent){06finalStringaction=intent.getAction();07if(Intent.ACTION_SCREEN_OFF.equals(action)){08//退出程序...09}10}11};12onCreate()方法中注册13IntentFilterfilter=newIntentFilter(Intent.ACTION_SCREEN_OFF);14registerReceiver(mBatInfoReceiver,filter);15onDestory()方法中解除注册16if(mBatInfoReceiver!=null){17try{18unregisterReceiver(mBatInfoReceiver);19}catch(Exceptione){20Log.e(TAG,"unregisterReceivermBatInfoReceiverfailure:"+e.getCause());21}22}

提醒:《android程序监听home键与电源键》最后刷新时间 2024-03-14 01:06:56,本站为公益型个人网站,仅供个人学习和记录信息,不进行任何商业性质的盈利。如果内容、图片资源失效或内容涉及侵权,请反馈至,我们会及时处理。本站只保证内容的可读性,无法保证真实性,《android程序监听home键与电源键》该内容的真实性请自行鉴别。