I faced the same problem as you did. So after researching some days I found below class for detecting (pressed event of home and recentapps keys).
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();
}
}
}
}
}
}
}
Use above class as below in onCreate method in your service.
@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();
}
and for detecting back press you can follow this link(Service with Overlay - catch back button press). I tested this solution and it worked for me.
So you can call stopService in onHomePressed() and onRecentAppsPressed() methods and then override onDestroy() method in your service class as below.
@Override
public void onDestroy() {
super.onDestroy();
mWindowManager.removeView(mYourOverlayView);
mHardwareKeyWatcher.stopWatch();
}
Please try these things and let us know... good luck.