12

I have an intent service which downloads several gigabytes of videos. I have a "Stop" button, to stop the download if accidentally hit "Start" or whatever. I know this has been asked a couple of times but with no working answer for me.

I try to call stopService(), doesn't work. That just calls IntentService.OnDestroy(). I tried to call stopSelf() inside onDestroy, doesn't work either.

I tried to have something like a flag, but onHandleIntent doesn't get called if its already running, it waits till current work is finished and executes then. And even if this would have worked, I would have to have something like a giant if statement, that sucks

Is my only option really to rewrite it to a regular Service?

//Answer

public class SyncService extends IntentService {

    boolean isCanceled;

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

        if (intent.hasExtra("action")) {

            // Set the canceling flag
            isCanceled= intent.getStringExtra("action").equals("cancel");

        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        // Clean up the possible queue
        if (intent.hasExtra ("action")) {
            boolean cancel = intent.getStringExtra ("action"). Equals ("cancel");
            if (cancel) {
                return;
            }
        }

        ...

        Get your inputStream from HttpUrlConnection or whatever

        ...

        while ((bytesRead = in.read(buffer)) > 0) {
            if (isCanceled) {
                isCanceled = false;
                break;
            }

            ...
        }

    }
}

And trigger it with

Intent intent = new Intent(context, SyncService.class);
intent.putExtra("action", "cancel");
context.startService(intent);
4

2 回答 2

12

你有两个不同的问题,我认为:

  1. 如何停止当前下载

  2. 如何停止排队下载,应该在当前下载完成后执行

第一个必须是“类似于标志的东西”,您在下载数据时进行检查。否则,没有什么可以阻止您的下载操作。如果您使用的是典型HttpUrlConnection配方,则在从 HTTP 读取InputStream并写入FileOutputStream. 您可以通过调用startService()特定Intent结构来设置该标志,将其标识为“取消”操作。您需要在onStartCommand()IntentService的.IntentIntentIntent

如果您可能有其他命令排队(场景#2),您还需要检查顶部的该标志onHandleIntent()

于 2013-04-18T22:15:30.490 回答
2

鉴于您尚未准确发布如何onHandleIntent处理视频下载,这可能不起作用(在执行下载的地方会有某种循环)。您可以在 中使用静态类变量IntentService来保存下载的停止/开始状态,以便可以通过Activity. 然后,在内部onHandleIntent,您必须定期检查状态,以便它知道何时取消操作。

于 2013-04-18T22:15:35.543 回答