一、需求

在应用开发过程中,启动服务开启线程锁等待服务返回解锁,为了避免点击home键使线程锁卡死的bug,需要监控home键,解锁线程。

二、实现

在应用时,需要register和unregister。

public class HomeWatcherReceiver extends BroadcastReceiver {
private static final String SYSTEM_DIALOG_REASON_KEY = "reason";
private static final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
private OnKeyListener listener; @Override
public void onReceive(Context context, Intent intent) { String intentAction = intent.getAction();
if (TextUtils.equals(intentAction, Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
if (TextUtils.equals(SYSTEM_DIALOG_REASON_HOME_KEY, reason)) {
listener.onHomeKey();
}
}
} public void registerHomeKeyReceiver(Context context) {
IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
context.registerReceiver(this, homeFilter);
} public void unregisterHomeKeyReceiver(Context context) {
context.unregisterReceiver(this);
} public void setListener(OnKeyListener listener) {
this.listener = listener;
} @FunctionalInterface
public interface OnKeyListener {
void onHomeKey();
}
}
04-20 00:14