监听android home键的实现方式
来源:互联网 发布:上海交大 知乎 编辑:程序博客网 时间:2024/06/06 13:24
1.首先是创建一个广播接受者
- private BroadcastReceiver mHomeKeyEventReceiver = new BroadcastReceiver() {
- String SYSTEM_REASON = "reason";
- String SYSTEM_HOME_KEY = "homekey";
- String SYSTEM_HOME_KEY_LONG = "recentapps";
-
- @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 (TextUtils.equals(reason, SYSTEM_HOME_KEY)) {
-
- Toast.makeText(getApplicationContext(), "home", 1).show();
- }else if(TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)){
-
- }
- }
- }
- };
2.注册监听可以在Activity里注册,也可以在Service里面
-
- registerReceiver(mHomeKeyEventReceiver, new IntentFilter(
- Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
完整的代码如下:- package com.example.homedemo;
-
- import android.os.Bundle;
- import android.app.Activity;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.content.IntentFilter;
- import android.text.TextUtils;
- import android.view.Menu;
- import android.widget.Toast;
-
- public class MainActivity extends Activity {
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
- registerReceiver(mHomeKeyEventReceiver, new IntentFilter(
- Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
- }
-
-
-
-
-
- private BroadcastReceiver mHomeKeyEventReceiver = new BroadcastReceiver() {
- String SYSTEM_REASON = "reason";
- String SYSTEM_HOME_KEY = "homekey";
- String SYSTEM_HOME_KEY_LONG = "recentapps";
-
- @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 (TextUtils.equals(reason, SYSTEM_HOME_KEY)) {
-
- Toast.makeText(getApplicationContext(), "home", 1).show();
- }else if(TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)){
-
- }
- }
- }
- };
- }
0 0