gpt4 book ai didi

android - Exoplayer如何显示下载进度

转载 作者:行者123 更新时间:2023-12-04 11:33:47 26 4
gpt4 key购买 nike

我正在尝试在 exoplayer 中下载离线视频,我想在 Activity 中显示下载进度。

如何绑定(bind)到 DownloadService在外层。以便我可以更新 Activity 中的当前下载进度?我尝试覆盖 onBind方法但没有onBind方法。

下载服务

class MediaDownloadService : DownloadService(
C.DOWNLOAD_NOTIFICATION_ID, 1000,
C.CHANNEL_ID, R.string.channel_name, R.string.channel_description
) {
private lateinit var downloadManager: DownloadManager

override fun onCreate() {
downloadManager = DownloadUtil.getDownloadManager(this)
downloadManager.addListener(object : DownloadManager.Listener {
override fun onDownloadChanged(downloadManager: DownloadManager, download: Download) {
if (download.bytesDownloaded == download.contentLength) {
toast("Download Completed!")
}
debug(download.failureReason)
}
})
super.onCreate()
}

override fun getDownloadManager(): DownloadManager {
return downloadManager
}

override fun getForegroundNotification(downloads: MutableList<Download>): Notification {
val intent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
val notificationHelper = DownloadNotificationHelper(this, C.CHANNEL_ID)

return notificationHelper.buildProgressNotification(
R.drawable.ic_notification,
pendingIntent,
"simple message",
downloads
)
}

override fun getScheduler(): Scheduler? {
return null
}

inner class DownloadBinder: Binder() {
val service: MediaDownloadService
get() = this@MediaDownloadService
}
}

最佳答案

在 Activity 中显示当前下载进度

  • 您需要覆盖并收听 DownloadTracker.Listener 这将使您了解下载的不同状态。
  • 当状态为 Download.STATE_DOWNLOADING启动协程/流程以将下载的当前值发送到您的 Activity 。
    我已经使用了这个流程(每 1 秒发送一次您想要的下载的 percentDownload 的值)

  • val downloadManager: DownloadManager // is set before in my object
    suspend fun getCurrentProgressDownload(uri: Uri?): Flow<Float?> {
    var percent: Float? = downloadManager.currentDownloads.find { it.request.uri == uri }?.percentDownloaded
    return callbackFlow {
    while(percent != null) {
    percent = downloadManager.currentDownloads.find { it.request.uri == uri }?.percentDownloaded
    offer(percent)
    withContext(Dispatchers.IO) {
    delay(1000)
    }
    }
    }
    }
  • 以你喜欢的方式展示

  • 我创建了一个存储库,您可以在其中查看 Activity 中的下载进度,这只是一个可以使用一些优化的示例。
    https://github.com/yoobi/exoplayer-kotlin/tree/master/downloadvideo/src/main/java/io/github/yoobi/downloadvideo
    如果有些事情不清楚,请毫不犹豫地问

    关于android - Exoplayer如何显示下载进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61840234/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com