如何在Kotlin中实现ContentObserver来监视DownloadManager的下载进度?

时间:2019-02-24 20:27:49

标签: android kotlin handler android-download-manager contentobserver

我选择“ DownloadManager的方式”来管理正在构建的应用程序的下载 我看到还有其他方法,例如AsyncTask,但是我可能还会面临大量下载,而且在我看来,DownloadManager可能比实现自己的下载器来管理线程更容易(我对kotlin和android并不熟悉)。 但是现在,我一直不知道如何将下载进度传递给View中的progressBar。 当然,首先我必须获得进度数据以监视下载;我找到了一个涉及创建ContentObserver的解决方案。 我将其从Java“翻译”为Kotlin,但是...我不明白如何以及如何以Handler身份传递

这是我的DownloadManager自定义类中的代码

var Download_Uri = android.net.Uri.parse(myUrl)

val request = DownloadManager.Request(Download_Uri)
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
request.setAllowedOverRoaming(false)

request.setTitle("$myTitle$myExtensionVar" + myTitle + myExtensionVar)
request.setDescription("Downloading " + myTitle + myExtensionVar)
request.setVisibleInDownloadsUi(true) //actually this doesn't work at all
request.setDestinationInExternalPublicDir(
    android.os.Environment.DIRECTORY_DOWNLOADS,
  "/" + myTitle + myExtensionVar
)

var refid:Long = downloadManager.enqueue(request)

// have I also to insert a while loop? Is creating a Thread for this right? I cannot find a really useful guide (for totally noobs) about threading...
Thread(Runnable {

    context.getContentResolver().registerContentObserver(Download_Uri, true, DownloadObserver(null)) // i put null cause I don't know what to insert here

}).start()

这是我的DownloadObserver类中的代码:

// i put a constructor to be able to pass also a null as "handler", I don't know if it's right, plus I don't know what to pass as handler object!
public class DownloadObserver constructor(var handler:Handler?): ContentObserver(handler) {

override fun onChange(selfChange: Boolean, uri: Uri) {
    Log.d("DownloadObserver", "my download at " + uri + " is updated...");
}

}

我在代码中插入了其他一些子问题作为注释。

提前致以最诚挚的问候! :)

0 个答案:

没有答案