在服务中不停止下载文件(非IntentService)

时间:2016-08-04 09:07:52

标签: android android-asynctask android-service android-download-manager

我有一个扩展服务的下载服务,我如何在其中下载文件,这样如果我从最近的应用程序中删除该应用程序,它会继续下载文件? 现在,如果我从最近的应用程序中删除该应用程序,它将停止下载:

代码的一部分:

public class downloadService extends Service {


        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {


                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
    //                publishProgress((int) ((total * 1000) / lenghtOfFile));
    //                mInfo.getProgressBar().setProgress((int) ((total * 1000) / lenghtOfFile));
    //                prog = (int) ((total * 1000) / lenghtOfFile);

                    // writing data to file
                    output.write(data, 0, count);
                    sendMessage(downloadId, (int) ((total * 1000) / lenghtOfFile));
                }

1 个答案:

答案 0 :(得分:0)

当用户从最近运行的应用中移除您的应用时,该应用的流程会被终止,因此您的Service也会立即停止。我没有意识到可以采取措施阻止这种情况发生。但是,您的Service可以在其START_STICKY中返回onStartCommand()之类的内容,这可能会重新启动Service。在那里,你自己应该处理重启场景(比如重启下载等)

与提到的OP一样,我们也可以尝试startForeground()从Play商店应用中获取提示Service。这可以使用:

完成
int NOTIF_ID = 0;
Notification notification = ...
    .build(); // notification instance
startForeground(NOTIF_ID, notification)