Why is my Service stopped when swiping app out of Recents?
<p>I declare my Service in the manifest like this:</p>

<pre><code>&lt;service
    android:name=".MyService"
    android:stopWithTask="false" /&gt;
</code></pre>

<p><strong>MyService.java:</strong></p>

<pre><code>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
    }
}
</code></pre>

<p>When i swipe out the app from Recents, <code>onTaskRemoved</code> runs as expected, but the <code>BroadcastReceiver</code>'s <code>onReceive</code> method does not get called anymore.</p>

<p>As far as i know, a <code>BroadcastReceiver</code>'s lifetime that's registered dynamically with <code>registerReceiver</code> is tied to the object that registered it. I think because of this, if my <code>Service</code> is still running, <code>onReceive</code> is supposed to be called.</p>

<p>I'm not sure if my <code>Service</code> stopped, or the <code>BroadcastReceiver</code> got unregistered.</p>

<p>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?</p>

<p>Edit:</p>

<p>I'm pretty sure my <code>Service</code> is still running, because the OS doesn't try to restart it (as it supposed to do if stopped because of <code>START_STICKY</code>), which means the problem is the <code>BroadcastReceiver</code> got unregistered. Why? (<code>onDestroy</code> does not get called)</p>

<p>Edit2:</p>

<p>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 <code>Service</code> is restarted immediately after stopping the task, as it supposed to (because of <code>START_STICKY</code>).</p>