Search code examples
androidkotlinandroid-download-managerexoplayer2.x

Listen for onDownloadComplete Exoplayer


I am trying to download a video for offline playing in exoplayer, but I don't know how to listen for onDownloadComplete. In the exoplayer docs they say DownloadService is a wrap around android DownloadManager so I try to listen for DownloadManager.ACTION_DOWNLOAD_COMPLETE broadcast but it's not working, actually this is my first time using exoplayer.

Download Service

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")
        }
    }
}

Solution

  • You can compare bytesDownloaded and contentLength to check if it's finish downloading.

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