中断从IntentService启动的特定线程



我正在尝试从服务器下载多个文件到我的设备。

这是我所做的:

活动
...
Intent intent = new Intent(this, DownloadService.class);
intent.putExtra(DownloadService.URL, url);
startService(intent);

DownloadService类

public class DownloadService extends IntentService {
...
    @Override
    protected void onHandleIntent(final Intent intent) {
        new Thread(new Runnable() {
        @Override
        public void run() {
            // Download code...
        }
    }).start();
}

我的IntentService可以从任何活动多次启动(例如,我想下载file0, file1,…, fileN):这就是为什么我使用线程内部onHandleIntent,以便分别下载它们。

这是我的问题:我怎么能取消/中断下载一个特定的线程,从IntentService启动?下载过程中没有UI更新,但只有一个带有进度条的通知,当然是从线程更新的。

一个文件的大小可以是1GB,我正在尝试撤销这个下载。

编辑1:

DownloadManager非常有用,我知道,但是我的文件是由多个子文件组成的,这些子文件是在运行时由服务器一个接一个地创建的。我已经尝试过这种方式,但这不是我想要的。

我终于解决了我的问题。

根据@CommonsWare的建议(再次感谢!)我创建了一个Service而不是IntentService,我用ThreadPoolExecutor在特定类中管理我的多个线程,每次由onStartCommand调用。

长话短说:我遵循了这个谷歌指南,我受到了ThreadSample项目的启发。

最新更新