1.首先是创建一个广播接受者
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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)) { //表示按了home键,程序到了后台 Toast.makeText(getApplicationContext(), "home", Toast.LENGTH_LONG).show(); }else if(TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)){ //表示长按home键,显示最近使用的程序列表 } } } }; |
2.注册监听
可以在Activity里注册,也可以在Service,Application里面
1 2 |
//注册广播 registerReceiver(mHomeKeyEventReceiver, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); |
完整的代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
import android.app.Application; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.text.TextUtils; import android.widget.Toast; public class MainApplication extends Application { /** * 监听是否点击了home键将客户端推到后台 */ 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)) { //表示按了home键,程序到了后台 Toast.makeText(getApplicationContext(), "home", Toast.LENGTH_LONG).show(); }else if(TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)){ //表示长按home键,显示最近使用的程序列表 } } } }; @Override public void onCreate() { super.onCreate(); //注册广播 registerReceiver(mHomeKeyEventReceiver, new IntentFilter( Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); } @Override public void onTerminate() { unregisterReceiver(mHomeKeyEventReceiver); super.onTerminate(); } } |
参考链接:监听android home键的实现方式