在android5.0项目开发遇到需要捕获HOME键的情况,经过查找,实现函数如下:

在framework/base/services/core/java/com/android/server/policy/PhoneWindowManager.java中添加如下函数:

    private boolean getTopStackActivity(String fullClassName){

        ActivityManager am = (ActivityManager)mContext.getSystemService(Context.ACTIVITY_SERVICE);

        RunningTaskInfo info = am.getRunningTasks(1).get(0);

        if(info == null || info.topActivity == null){

            Log.e(TAG, "Top activity is null, error");

            return false;

        }

        if(fullClassName.equals(info.topActivity.getClassName())){

            Log.d(TAG, "Top Activity:"+info.topActivity.getClassName());

            return true;

        }

        return false;

    }

  1. HOME键处理:

    在 interceptKeyBeforeDispatching函数的if(keyCode == KeyEvent.KEYCODE_HOME)中添加如上函数即可在应用层捕获HOME键。

  2. APP_SWITCH键处理:

    在interceptKeyBeforeDispatching函数的else if(keyCode == KeyEvent.KEYCODE_MENU)下的if(keyCode == KeyEvent.KEYCODE_APP_SWITCH)中添加如上函数即可在应用层捕获APP_SWITCH键。