一、使用注册广播监听home键、多任务键
class InnerRecevier extends BroadcastReceiver {
final String SYSTEM_DIALOG_REASON_KEY = "reason";
final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
if (reason != null) {
if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
Toast.makeText(MainActivity.this, "Home键被监听", Toast.LENGTH_SHORT).show();
} else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
Toast.makeText(MainActivity.this, "多任务键被监听", Toast.LENGTH_SHORT).show();
}
}
}
}
}
在Activity中的onCreate()方法中注册广播,代码如下:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//创建广播
InnerRecevier innerReceiver = new InnerRecevier();
//动态注册广播
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
//启动广播
registerReceiver(innerReceiver, intentFilter);
}