2

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).

  • See this https://stackoverflow.com/questions/20677781/in-android-4-4-swiping-app-out-of-recent-tasks-permanently-kills-application-wi 100% help you.. – Gundu Bandgar Jul 10 '17 at 07:37

1 Answers1

0

Check the workaround to handle the service after the restart from the SO link:

The process of the service is killed after the application is removed from the application tray

Community
  • 1
  • 1
user492888
  • 207
  • 3
  • 17