zoukankan      html  css  js  c++  java
  • Home键的获取监听,安卓4.0后就不能在onkeydown方法中获取了。怎么办。

    Android下得到Home键按下的消息

     

    在Android下,并不能通过onKeyDown这样的事件来截获Home键的消息,其原因在Android的文档中已经明确的说过了

    Android下得到Home键按下的消息

    public static final int KEYCODE_HOME

    Key code constant:Home key.This key is handled by the framework and is never delivered to applications.

    Constant Value:3(0x00000003)

    翻译就不做了,总之就是App无法截获Home键的事件(曾经有高人在2.3以下的系统中,使用偏门方法来截获Home,但是在4.0以后已经失效了,故在此不提)

    那么,如何才能得到Home键按下的消息呢,办法还是有的,在此需要说明的是,由于Home键的特殊性,它的逻辑在framework内被处理,因此无法 做到截获/屏蔽Home键,而只能得到它的消息,但是在得到消息后,如果要把已经退到后台的app再启动起来,也并非不能(界面会闪一下)

    以下代码用于捕捉到Home键的按下消息:

    Android下得到Home键按下的消息

    public class HomeReceiver extends BroadcastReceiver{

    @override

    public void onReceive(Context context,Intent intent){

    String action=intent.getAction();

    if(action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)){

    String reason=intent.getStringExtra("reason");

    if(reason!=null){

    if(reason.equals("homekey")){

    //home pressed

    }else if(reason.equals("recentapps")){

    //recentapps pressed

    }

    }

    }

    }

    同时,我们也需要将这个receiver注册到程序中,以便使它生效

    Android下得到Home键按下的消息

    public HomeReceiver receiverHome=new HomeReceiver();

    public IntentFilter filterHome=new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);

    @override

    protected void onCreate(Bundle savedInstanceState){

    super.onCreate(savedInstanceState);

    registerReceiver(receiverHome,filterHome);

    }

    @override

    protected void onDestroy(){

    unregisterReceiver(receiverHome);

    super.onDestroy();

    }

    这样,在上述两个TODO处,即可添加自己的代码,需要注意的是,在4.0以后,home键可能有两种reason,分别是原本的Home与显示最近的应用,在receiver中,通过判断reason字符串,可以分别处理。

  • 相关阅读:
    luogu P1330 封锁阳光大学
    P4817 [USACO15DEC]Fruit Feast 水果盛宴
    P2041 分裂游戏
    洛谷——P3373 【模板】线段树 2&& B 数据结构
    洛谷——P1471 方差
    洛谷——P1073 最优贸易
    洛谷——P1516 青蛙的约会
    洛谷——P1962 斐波那契数列
    洛谷——P3811 【模板】乘法逆元
    58到家数据库30条军规解读
  • 原文地址:https://www.cnblogs.com/yaya-Android/p/4123524.html
Copyright © 2011-2022 走看看