androidkotlinandroid-download-manager

Not receive DOWNLOAD_COMPLETE broadcast when download complete


I create an app with an update feature, my app is now able to detect the update and download it but when the download complete, DownloadReceiver is not triggered and I don't know why

I have a class AppUpdater like this:

class AppUpdater(private val context: Context) {
    private lateinit var apkUrl: String
    private var downloadId: Long = -1
    var isUpdateAvailable = mutableStateOf(false)

    val downloadManager: DownloadManager = context.getSystemService(DownloadManager::class.java)

    fun checkForUpdates() {
        HttpHandler.asyncHandle(Constant.UPDATE_URL, Constant.AUTHORIZATION_TOKEN, ::callback)
    }

    private fun callback(response: okhttp3.Response) {...}

    fun downloadApkFile() {
        val request = DownloadManager.Request(Uri.parse(apkUrl))
            .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
            .addRequestHeader("Authorization", "Bearer ${Constant.AUTHORIZATION_TOKEN}")
            .addRequestHeader("Accept", "application/octet-stream")
            .setDestinationInExternalPublicDir(
                Environment.DIRECTORY_DOWNLOADS,
                "MyApp.apk"
            )
            .setAllowedOverMetered(true)
            .setAllowedOverRoaming(true)
        downloadId = downloadManager.enqueue(request)
    }

    inner class DownloadReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            Log.w("AppUpdater", "APK Download Complete")
            val id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
            if (id == downloadId) {...}
        }
    }
}

And in AndroidManifest.xml, I register this receiver:

<receiver
    android:name=".AppUpdater$DownloadReceiver"
    android:exported="false">
    <intent-filter>
        <action android:name="android.intent.action.DOWNLOAD_COMPLETE" />
    </intent-filter>
</receiver>

Solution

  • I think the problem could be that you register this receiver via manifest, and android has limitations to this kind of registering or it may be fact that exported flag is set to false.

    First try set this flag to true and if this not resolves issue try register receiver with context.