1、介绍ACTION_CLOSE_SYSTEM_DIALOGS
/**
* Broadcast Action: This is broadcast when a user action should request a
* temporary system dialog to dismiss. Some examples of temporary system
* dialogs are the notification window-shade and the recent tasks dialog.
*/
public static final String ACTION_CLOSE_SYSTEM_DIALOGS = "android.intent.action.CLOSE_SYSTEM_DIALOGS";
按Home键和菜单键会收到消息
2、相关文件
HomeListener.java
package com.example.homekey;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
public class HomeListener {
public KeyFun mKeyFun;
public Context mContext;
public IntentFilter mHomeBtnIntentFilter = null;
public HomeBtnReceiver mHomeBtnReceiver = null;
public static final String TAG = "HomeListener";
public HomeListener(Context context) {
mContext = context;
mHomeBtnIntentFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
mHomeBtnReceiver = new HomeBtnReceiver();
}
public void startListen() {
if (mContext != null )
mContext.registerReceiver(mHomeBtnReceiver, mHomeBtnIntentFilter);
else
Log.e(TAG, "mContext is null and startListen fail");
}
public void stopListen() {
if (mContext != null )
mContext.unregisterReceiver(mHomeBtnReceiver);
else
Log.e(TAG, "mContext is null and stopListen fail");
}
public void setInterface(KeyFun keyFun){
mKeyFun = keyFun;
}
class HomeBtnReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
String reason = intent.getStringExtra("reason");
if (reason != null) {
if(null != mKeyFun ){
if (reason.equals("homekey")) {
//按Home按键
mKeyFun.home();
} else if (reason.equals("recentapps")) {
//最近任务键也就是菜单键
mKeyFun.recent();
} else if (reason.equals("assist")) {
//常按home键盘
mKeyFun.longHome();
}
}
}
}
}
}
public interface KeyFun {
public void home();
public void recent();
public void longHome();
}
}
MainActivity.java
package com.example.homekey;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
public class MainActivity extends ActionBarActivity {
public static final String TAG = "TestHome";
private HomeListener mHomeListen = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHomeListen = new HomeListener(this);
mHomeListen.setInterface(new HomeListener.KeyFun() {
@Override
public void recent() {
Log.d(TAG, "recent");
}
@Override
public void longHome() {
Log.d(TAG, "longHome");
}
@Override
public void home() {
Log.d(TAG, "home");
}
});
}
@Override
protected void onResume( ) {
super.onResume();
mHomeListen.startListen();
}
@Override
protected void onPause() {
super.onPause();
mHomeListen.stopListen();
}
}