Android 5.0 Intercept HomeKey
一、拦截Home键的多种方式介绍
1.1 重写onAttachedToWindow、onKeyDown
1.2 重写onSaveInstanceState
1.3 重写onUserLeaveHint
1.4 监听广播Intent.ACTION_CLOSE_SYSTEM_DIALOGS
Android 4.4 之前版本,前三种方式都是可以拦截到的,第四种未确认。4.4之后的系统前三种已经失效,因为在系统Frameworks层已经做了拦截,Application层只能用第四种方式监听广播。
二、封装监听广播接口
public class KeypadIntercept {private static final String TAG = "KeypadIntercept";private Context mContext;private IntentFilter mFilter;private OnKeypadListener mListener;private HomeKeyRecevier mRecevier;// 广播携带String类型参数final String SYSTEM_DIALOG_REASON_KEY = "reason";// 切换应用程序键final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";// Home键final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";// 申明按键事件监听接口public interface OnKeypadListener {void onHomeKeypadPressed();void onRecentKeypadPressed();void onKeypadError();}public KeypadIntercept(Context context) {mContext = context;mRecevier = new HomeKeyRecevier();// 实例化的时候给Intent添加广播mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);}public void setOnKeypadListener(OnKeypadListener listener) {mListener = listener;}public void startListener() {if (mRecevier != null) {// 动态注册广播mContext.registerReceiver(mRecevier, mFilter);}}public void stopListener() {if (mRecevier != null) {// 注销广播mContext.unregisterReceiver(mRecevier);}}class HomeKeyRecevier extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {String reasonKey = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);if (reasonKey != null) {if (mListener != null) {Log.i(TAG, "Action= " + action + ", reason= " + reasonKey);switch (reasonKey) {case SYSTEM_DIALOG_REASON_HOME_KEY:mListener.onHomeKeypadPressed();break;case SYSTEM_DIALOG_REASON_RECENT_APPS:mListener.onRecentKeypadPressed();break;default:mListener.onKeypadError();break;}}}}}}
}
三、Activity使用实例 public class MainActivity extends AppCompatActivity {KeypadIntercept mKeypadIntercept;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mKeypadIntercept = new KeypadIntercept(MainActivity.this);mKeypadIntercept.startListener();mKeypadIntercept.setOnKeypadListener(new KeypadIntercept.OnKeypadListener() {@Overridepublic void onHomeKeypadPressed() {Toast.makeText(MainActivity.this, "onHomeKeypadPressed", Toast.LENGTH_LONG).show();}@Overridepublic void onRecentKeypadPressed() {Toast.makeText(MainActivity.this, "onRecentKeypadPressed", Toast.LENGTH_LONG).show();}@Overridepublic void onKeypadError() {Toast.makeText(MainActivity.this, "onKeypadError", Toast.LENGTH_LONG).show();}});}@Overrideprotected void onDestroy() {super.onDestroy();mKeypadIntercept.stopListener();}
}