Tôi gặp phải vấn đề tương tự như bạn đã làm. Vì vậy, sau khi nghiên cứu một số ngày tôi tìm thấy bên dưới lớp học để phát hiện (sự kiện ép của nhà và các khóa ứng dụng gần đây).
public class HardwareKeyWatcher {
static final String TAG = "HardwareKeyWatcher";
private Context mContext;
private IntentFilter mFilter;
private OnHardwareKeysPressedListener mListener;
private InnerReceiver mReceiver;
public interface OnHardwareKeysPressedListener {
public void onHomePressed();
public void onRecentAppsPressed();
}
public HardwareKeyWatcher(Context context) {
mContext = context;
mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
mFilter.setPriority(1000);
}
public void setOnHardwareKeysPressedListenerListener(OnHardwareKeysPressedListener listener) {
mListener = listener;
mReceiver = new InnerReceiver();
}
public void startWatch() {
if (mReceiver != null) {
mContext.registerReceiver(mReceiver, mFilter);
}
}
public void stopWatch() {
if (mReceiver != null) {
mContext.unregisterReceiver(mReceiver);
}
}
class InnerReceiver 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 (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
if (reason != null) {
Log.e(TAG, "action:" + action + ",reason:" + reason);
if (mListener != null) {
if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
mListener.onHomePressed();
} else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
mListener.onRecentAppsPressed();
}
}
}
}
}
}
}
Sử dụng lớp học trên như dưới đây trong phương phápTạo hiện tại trong dịch vụ của bạn.
@Override
public void onCreate() {
mHardwareKeyWatcher = new HardwareKeyWatcher(this);
mHardwareKeyWatcher.setOnHardwareKeysPressedListenerListener(new HardwareKeyWatcher.OnHardwareKeysPressedListener() {
@Override
public void onHomePressed() {
System.out.println("stop your service here");
}
@Override
public void onRecentAppsPressed() {
System.out.println("stop your service here");
}
});
mHardwareKeyWatcher.startWatch();
}
và để phát hiện báo chí, bạn có thể đi theo liên kết này (Service with Overlay - catch back button press). Tôi đã thử nghiệm giải pháp này và nó đã làm việc cho tôi.
Vì vậy, bạn có thể gọi stopService trong phương thức onHomePressed() và onRecentAppsPressed() và sau đó ghi đè lên phương thứcDestroy() trong lớp dịch vụ của bạn như dưới đây.
@Override
public void onDestroy() {
super.onDestroy();
mWindowManager.removeView(mYourOverlayView);
mHardwareKeyWatcher.stopWatch();
}
Hãy thử những điều này và cho chúng tôi biết ... chúc may mắn.
Nó hoạt động như một sự quyến rũ. Cảm ơn rất nhiều. – Ajeet