• android程序监听home键与电源键


    01 private final BroadcastReceiver homePressReceiver = new BroadcastReceiver() {
    02 final String SYSTEM_DIALOG_REASON_KEY = "reason";
    03 final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
    04 @Override
    05 public void onReceive(Context context, Intent intent) {
    06 String action = intent.getAction();
    07 if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
    08 String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
    09 if (reason != null && reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
    10 //自己随意控制程序,关闭...
    11 }
    12 }
    13 }
    14 };

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

    1 final IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
    2 registerReceiver(homePressReceiver, homeFilter);

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

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

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

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

    然后监听两个action

    01 Intent.ACTION_SCREEN_OFF
    02 Intent.ACTION_SCREEN_ON
    03 private final BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
    04 @Override
    05 public void onReceive(final Context context, final Intent intent) {
    06 final String action = intent.getAction();
    07 if (Intent.ACTION_SCREEN_OFF.equals(action)) {
    08 //退出程序...
    09 }
    10 }
    11 };
    12 onCreate()方法中注册
    13 IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
    14 registerReceiver(mBatInfoReceiver, filter);
    15 onDestory()方法中解除注册
    16 if(mBatInfoReceiver != null){
    17 try {
    18 unregisterReceiver(mBatInfoReceiver);
    19 catch (Exception e) {
    20 Log.e(TAG, "unregisterReceiver mBatInfoReceiver failure :"+e.getCause());
    21 }
    22 }
  • 相关阅读:
    Android_listview设置每条信息的间距
    Android实现ListView或GridView首行/尾行距离屏幕边缘距离
    实现类似微信的延迟加载的Fragment——LazyFragment
    struts2的Action该方法不能去
    (工具)source insight高速增加时间代码
    猫学习IOS(十五)UI以前的热的打砖块游戏
    java语言内部类和匿名内部类
    JVM截至多少线程可以创建: unable to create new native thread
    linux下一个Oracle11g RAC建立(八)
    转基因小麦--主题在农业科技的最前沿
  • 原文地址:https://www.cnblogs.com/xiaochao1234/p/3611206.html
Copyright © 2020-2023  润新知