监听 onDownloadComplete Exoplayer

Listen for onDownloadComplete Exoplayer

我正在尝试下载一个视频在 exoplayer 中离线播放,但我不知道如何监听 onDownloadComplete。在 exoplayer 文档中,他们说 DownloadService 是 android DownloadManager 的环绕,所以我尝试收听 DownloadManager.ACTION_DOWNLOAD_COMPLETE 广播,但它不起作用,实际上这是我第一次使用 exoplayer .

下载服务

class MediaDownloadService : DownloadService(
    C.DOWNLOAD_NOTIFICATION_ID, DEFAULT_FOREGROUND_NOTIFICATION_UPDATE_INTERVAL,
    C.CHANNEL_ID, R.string.channel_name, R.string.channel_description
) {
    override fun onCreate() {
        registerReceiver(onComplete, IntentFilter(ACTION_DOWNLOAD_COMPLETE))
        super.onCreate()
    }

    override fun onDestroy() {
        unregisterReceiver(onComplete)
        super.onDestroy()
    }

    override fun getDownloadManager(): DownloadManager {
        return DownloadUtil.getDownloadManager(this)
    }

    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
    }


    val onComplete: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(ctxt: Context?, intent: Intent?) {
            toast("Download COmpleted")
        }
    }
}

您可以比较bytesDownloadedcontentLength来检查是否完成下载。

downloadManager.addListener(object : DownloadManager.Listener {
    override fun onDownloadChanged(downloadManager: DownloadManager, download: Download) {
        if (download.bytesDownloaded == download.contentLength) {
            Log.d("Completed")
        }
    }
})