- 關于home鍵的監聽,下面的方法是不管用的, 當然正常的BACK還是可以用的
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_HOME){
L.e("按home鍵,這里是走不到的!");
}
}
- 解決辦法就是按home鍵,系統會發送一個廣播
- public static final String ACTION_CLOSE_SYSTEM_DIALOGS = "android.intent.action.CLOSE_SYSTEM_DIALOGS";所以就需要在廣播中捕捉這個action來做處理了。
- 下面的代碼
public class HomeReceiverUtil {
static final String SYSTEM_DIALOG_REASON_KEY = "reason";
static final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
private static BroadcastReceiver mHomeReceiver = null;
/**
* 添加home的廣播
* @param context
*/
public static void registerHomeKeyReceiver(Context context , final HomeKeyListener listener) {
L.d("注冊home的廣播");
mHomeReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
homeFinish(intent , context , listener);
}
};
final IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
context.registerReceiver(mHomeReceiver, homeFilter);
}
/**
* 注銷home的廣播
* @param context
*/
public static void unregisterHomeKeyReceiver(Context context) {
L.d( "銷毀home的廣播");
if (null != mHomeReceiver) {
context.unregisterReceiver(mHomeReceiver);
mHomeReceiver = null ;
L.d("已經注銷了,不能再注銷了");
}
}
private static void homeFinish(Intent intent, Context context, HomeKeyListener listener) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
if (reason != null && reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
if (listener != null){
listener.homeKey();
}
}
}
}
//回調接口, 當然可以自己自行處理
public interface HomeKeyListener{
void homeKey();
}
}
- 下面就是在activity中的使用
這里的this要格外注意一下!這里的this要格外注意一下!這里的this要格外注意一下!
使用this了 必須在onPause中解綁,因為生命周期是先走onPause 在onCreate..的
當然吧this替換成getApplicationContext() 了 OnPause, onStop , onDestroy都可以解綁,
把下面的寫到BaseActivity中就可以了
//監聽home按鍵
//onCreate,onResume注冊都行
HomeReceiverUtil.registerHomeKeyReceiver(this, new HomeReceiverUtil.HomeKeyListener() {
@Override
public void homeKey() {
Toast.makeText(HomeActivity.this, "這里做些處理", Toast.LENGTH_SHORT).show();
}
});
//記住,使用this了 必須在onPause中解綁,生命周期的原因!
HomeReceiverUtil.unregisterHomeKeyReceiver(this);