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

末鹿安然 提交于 2019-12-12 02:23:15

问题


I have a downloader app project and I'm using a Service class for managing download tasks and showing notifications like this : 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 ?!


回答1:


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



来源:https://stackoverflow.com/questions/39367549/background-service-for-multitask-downloader-stops-when-close-app-from-recent-ap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!