当关闭“最新应用"中的应用时,多任务下载器的后台服务停止. [英] background service for multitask downloader stops when close app from "recent apps"

查看:75
本文介绍了当关闭“最新应用"中的应用时,多任务下载器的后台服务停止.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个下载器应用程序项目,并且正在使用Service类来管理下载任务并显示如下通知:问题:当我通过滑动从最近的应用程序中关闭应用程序时,该服务将停止.我不能使用 startForeground 进行通知,因为我在一项服务中有多个通知.而且我喜欢 notify.setAutoCancel(true)可以正常工作.这是AndroidManifest.xml代码:

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" />

这是启动服务:

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);
}

这是 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;
}

我该如何解决?!

推荐答案

当您返回 START_STICKY 时,此服务将在您关闭/杀死该应用程序时停止,因为在该应用程序关闭了所有引用/值之后对于所有Intent以及变量,它将变为 null ,因此 STICKY 服务将无法获得Intent值.

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.

要在应用终止后继续服务,请使用返回START_REDELIVER_INTENT

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;
}

看到相同的问题此处

这篇关于当关闭“最新应用"中的应用时,多任务下载器的后台服务停止.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆