android home键带来的问题


问题1:监听home键
第一种方式:android 对home键的监听,加上了权限,必须取得对处理home键事件的权限,才能对home键进行操作,
只对2.2及以前的系统有效。
     1,加上权限
      <uses-permission android:name="android.permission.DISABLE_KEYGUARD"/>
     就是让键盘守卫失去能了,根据英文大体是这个意思
     2,重载以下两个方法@Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
      if(KeyEvent.KEYCODE_HOME==keyCode){
        //写要执行的动作或者任务
        
      }
      return super.onKeyDown(keyCode, event);
  }
  @Override
  public void onAttachedToWindow(){
      this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
      super.onAttachedToWindow();
  }
第二种方式:通过广播方式监听
   class HomeKeyEventBroadCastReceiver extends BroadcastReceiver {
        static final String SYSTEM_REASON = "reason";
        static final String SYSTEM_HOME_KEY = "homekey";//home key
        static final String SYSTEM_RECENT_APPS = "recentapps";//long home key
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYSTEM_REASON);
                if (reason != null) {
                    if (reason.equals(SYSTEM_HOME_KEY)) {
//                     System.out.println("***************home key处理点 ***************");
                        // home key处理点
                     DemoApplication.Home_key=true;
//                     showNotification();
                    } else if (reason.equals(SYSTEM_RECENT_APPS)) {
                        // long home key处理点
                    }
                }
            }
        }
   }
   注册广播
   HomeKeyEventBroadCastReceiver receiver = new HomeKeyEventBroadCastReceiver();
   registerReceiver(receiver, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));

问题2:安装系统SD卡里面的apk或者原有的程序更新版本的时候,会遇到升级安装成功之后的一个选择——“打开”和“完成”,点击完成没有问题,但是,如果点击了"打开",然后按Home键,从应用程序列表里面选择应用程序图标进入,这个时候就会重新启动了一个应用程序,退出之后就正常了。
解决方案:监听home键,当home后设全局变量DemoApplication.Home_key=true;然后启动应用的时候判断DemoApplication.Home_key
  if(DemoApplication.Home_key){//home键后点击应用入口
 finish();
  }else{
 //正常启动入口
  }
或者在程序入口的activity中检测该activity是不是程序的root Activity。如果不是就可以直接finish此activity,程序会从栈中还原以前的状态。
具体代码如下:
在应用启动的activity的Oncreate方法中添加如下代码即可:
 if (!isTaskRoot()) {
     // Android launched another instance of the root activity into an existing task
     //  so just quietly finish and go away, dropping the user back into the activity
     //  at the top of the stack (ie: the last state of this task)
     finish();
     return;
 }else{
 }
问题3:返回键模拟home键,
Intent intent2 = new Intent();
intent2.setAction(Intent.ACTION_MAIN);
intent2.addCategory(Intent.CATEGORY_HOME);
startActivity(intent2);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章