lingochamp / okdownload

A Reliable, Flexible, Fast and Powerful download engine.
Apache License 2.0
5.19k stars 776 forks source link

About findOrCreateId question #397

Open nukc opened 4 years ago

nukc commented 4 years ago

OkDownload Version

v1.0.7

Problem Describe

自己维护了一个下载文件的数据库表,查询列表的时候就进行了 task 的创建并与自己的 item 进行了关联。 RecycleView 绑定的数据是 item 数组,动态添加下载

val item = ....
val task = createTask(url, uri, fileName)
task.enqueue(downloadListener)
item.task = task
items.add(0, item)

多试几次后发现 task 的 id 是有重复的(并不指 OkDownload 内部维护的 id list 有重复),下载地址 url 是一样的,uri 和 filename 都不一样

下载完成之后,remove 掉了,下次 build task 还可以是之前用过的 id

  @Override public synchronized void remove(int id) {
        storedInfos.remove(id);
        if (unStoredTasks.get(id) == null) sortedOccupiedIds.remove(Integer.valueOf(id));
        keyToIdMap.remove(id);
    }

然后当通过 getCurrentInfo 获取 BreakpointInfo 就混乱了

    @Nullable public static BreakpointInfo getCurrentInfo(@NonNull DownloadTask task) {
        final BreakpointStore store = OkDownload.with().breakpointStore();
        final int id = store.findOrCreateId(task);

        final BreakpointInfo info = store.get(id);

        return info == null ? null : info.copy();
    }

杀应用重新打开(初始化列表的时候,每个 item 都 build task 了),id 都不会有重复。但动态添加就会重复 id。

Log

item.id 是数据库自增,task.id 重复了

E/DownloadManager: item.id = 41 ---  task.id = 32
E/DownloadManager: taskStart
E/DownloadManager: connected, currentOffset=0, totalLength=11215669
E/DownloadManager: progress
E/DownloadManager: progress
E/DownloadManager: progress
E/DownloadManager: progress
E/DownloadManager: taskEnd
E/DownloadManager: item.id = 42 ---  task.id = 32
E/DownloadManager: taskStart
E/DownloadManager: connected, currentOffset=0, totalLength=11215669
E/DownloadManager: progress
E/DownloadManager: progress
E/DownloadManager: progress
E/DownloadManager: progress
E/DownloadManager: taskEnd

通过继承 BreakpointStoreOnCache 并覆写 remove(int id),然后测试 id 不再重复

    @Override
    public synchronized void remove(int id) {
//        super.remove(id);
    }