Search code examples
androidservicebackground-processandroid-download-managerbackground-service

background service for multitask downloader stops when close app from "recent apps"


I have a downloader app project and I'm using a Service class for managing download tasks and showing notifications like this : enter image description here the problem: when I close app from recent apps by swiping , the Service will be stop. I cant use startForeground for notifications , because I have multiple notifications in one service . and I like notify.setAutoCancel(true) works fine. here is AndroidManifest.xml code :

<service android:name=".Downloader"  android:exported="false" android:enabled="true"
android:stopWithTask="false" />

here is starting service :

public static void intentDownload(Context context , FileInfo info) {
    Intent intent = new Intent(context, Downloader.class);
    intent.setAction(ACTION_DOWNLOAD);
    intent.putExtra(EXTRA_TAG, info.Tag);
    intent.putExtra(EXTRA_APP_INFO, info);
    context.startService(intent);
}

and here is onStartCommand :

 public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null) {
        String action = intent.getAction();
        FileInfo fInfo;
        String tag = intent.getStringExtra(EXTRA_TAG);
        switch (action) {
            case ACTION_DOWNLOAD:
                fInfo = (FileInfo) intent.getSerializableExtra(EXTRA_APP_INFO);
                download(fInfo);
                break;
            case ACTION_PAUSE:
                fInfo = (FileInfo) intent.getSerializableExtra(EXTRA_APP_INFO);
                pause(fInfo);
                break;
            case ACTION_CANCEL:
                cancel(tag);
                break;
            case ACTION_PAUSE_ALL:
                pauseAll();
                break;
            case ACTION_CANCEL_ALL:
                cancelAll();
                break;
        }
    } 
    return Service.START_STICKY;
}

how can I fix it ?!


Solution

  • As you are returning START_STICKY this service will stop whenever you close/kill the app because after the App closed all the Reference/Value will become null for all Intent as well as variables and so STICKY service will not able to get Intent value.

    To continue service after app kills use return START_REDELIVER_INTENT

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_REDELIVER_INTENT;
    }
    

    See same problem Here