如何在前台服务中排队多个任务,以便它们一个接一个地执行?

时间:2019-04-20 20:26:44

标签: android android-asynctask android-service android-intentservice

public class CopyService extends Service {

private List<CustomFile> taskList;
private AsyncTask fileTask;

@Override
public void onCreate() {
    super.onCreate();
    taskList = new ArrayList<>();
    fileTask = new fileTaskAsync();
}

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

    String filePath = intent.getStringExtra("filePath");
    String fileType = intent.getStringExtra("fileType");
    String taskType = intent.getStringExtra("taskType");
    String fileName = intent.getStringExtra("fileName");

    CustomFile customFile = new CustomFile();
    customFile.filePath = filePath;
    customFile.fileType = fileType;
    customFile.taskType = taskType;
    customFile.fileName = fileName;
    taskList.add(customFile);

    Notification notification = getNotification();

    startForeground(787, notification);

    if (fileTask.getStatus() != AsyncTask.Status.RUNNING) {

        CustomFile current = taskList.get(0);
        taskList.remove(current);

        fileTask = new fileTaskAsync().execute(current);
    }

    stopSelf();
    return START_NOT_STICKY;
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

private class fileTaskAsync extends AsyncTask<CustomFile, Void, String> {

    @Override
    protected String doInBackground(CustomFile... customFiles) {

        CustomFile customFile = customFiles[0];

        FileUtils.doFileTask(customFile.filePath, customFile.fileType,
                customFile.taskType);

        return customFile.fileName;
    }

    @Override
    protected void onPostExecute(String name) {
        sendResult(name);

        if (!taskList.isEmpty()) {
            CustomFile newCurrent = taskList.get(0);
            taskList.remove(newCurrent);
            fileTask = new fileTaskAsync().execute(newCurrent);
        }
    }
}

private void sendResult(String name) {
    Intent intent = new Intent("taskStatus");
    intent.putExtra("taskName", name);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

}

我需要在服务中一个接一个地执行多个任务。任务是复制或移动本地文件。假设用户正在复制一个大文件,而他想复制或移动其他文件。我需要将后续任务排入队列,并逐个执行。

当前,我正在服务内部创建列表并运行异步任务。在onPostExecute中,我检查列表中是否还有剩余任务,然后从那里再次启动异步任务。如代码所示。

但是,我担心内存泄漏。而且我对编程还很陌生,所以我不知道在这种情况下的最佳实践是什么。

我不能使用IntentService,因为即使用户按下主屏幕按钮打开其他应用,我也希望任务继续执行。

1 个答案:

答案 0 :(得分:1)

正如我在评论中所说,我认为您的解决方案是合理的。前景Service是需要立即执行的长期运行工作的理想人选,并且根据您的描述,文件复制任务符合该条件。

也就是说,我不认为AsyncTask是解决您问题的合适人选。当您需要在主线程上进行一些快速工作时,最好最多部署AsyncTasks,最多最多几百毫秒,而复制任务可能要花费几秒钟。

由于您要完成多个任务,而这些任务并不直接相互依赖,因此我建议您利用线程池来完成这项工作。为此,您可以使用ExecutorService

public class CopyService extends Service {

private final Deque<CustomFile> tasks = new ArrayDeque<>();
private final Deque<Future<?>> futures = new LinkedBlockingDequeue<>();
private final ExecutorService executor = Executors.newCachedThreadPool();

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

    //May as well add a factory method to your CustomFile that creates one from an Intent
    CustomFile customFile = CustomFile.fromIntent(intent);
    tasks.offer(customFile);

    //...Add any other tasks to this queue...

    Notification notification = getNotification();

    startForeground(787, notification);

    for(CustomFile file : tasks) {
       final Future<?> future = executor.submit(new Runnable() {
           @Override
           public void run() {
               final CustomFile file = tasks.poll();
               //Ddo work with the file...
               LocalBroadcastManager.getInstance(CopyService.this).sendBroadcast(...);
               //Check to see whether we've now executed all tasks. If we have, kill the Service.
               if(tasks.isEmpty()) stopSelf();
           }
       });
       futures.offer(future);
    }
    return START_NOT_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();
    //Clear pending and active work if the Service is being shutdown
    //You may want to think about whether you want to reschedule any work here too
    for(Future<?> future : futures) {
        if(!future.isDone() && !future.isCancelled()) {
            future.cancel(true); //May pass "false" here. Terminating work immediately may produce side effects.
        } 
    }
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

这不会引起任何内存泄漏,因为所有待处理的工作都会与服务一起被破坏。