I declare my Service in the manifest like this:
<service
android:name=".MyService"
android:stopWithTask="false" />
MyService.java:
public class MyService extends Service {
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// doing stuff
}
};
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
public void onCreate() {
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_TIME_TICK);
registerReceiver(receiver, filter);
}
@Override
public void onDestroy() {
// does not get called
unregisterReceiver(receiver);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onTaskRemoved(Intent rootIntent) {
// this method get called when i remove the task from recents
}
}
When i swipe out the app from Recents, onTaskRemoved runs as expected, but the BroadcastReceiver's onReceive method does not get called anymore.
As far as i know, a BroadcastReceiver's lifetime that's registered dynamically with registerReceiver is tied to the object that registered it. I think because of this, if my Service is still running, onReceive is supposed to be called.
I'm not sure if my Service stopped, or the BroadcastReceiver got unregistered.
Either way, how can i prevent them from stopping when the task is removed from recents? If i cannot, is there a way to restart it immediately?
Edit:
I'm pretty sure my Service is still running, because the OS doesn't try to restart it (as it supposed to do if stopped because of START_STICKY), which means the problem is the BroadcastReceiver got unregistered. Why? (onDestroy does not get called)
Edit2:
Found the problem. It's the device i was testing on. I was using a Xiaomi Redmi Note 2 with MIUI android ROM. Seems when swiping out from recents in MIUI, the OS kills the whole process (pretty much as a task killer does), not just the task.
Testing on my other devices the Service is restarted immediately after stopping the task, as it supposed to (because of START_STICKY).