首页 > 解决方案 > 如何以编程方式安装下载的 APK 文件?

问题描述

以下是下载完成后下载和安装apk文件的代码。但是我下载后无法打开apk文件。

private fun downloadAPk(apkUrl: String) {
        val request = DownloadManager.Request(Uri.parse(apkUrl))
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
        request.setTitle("Customer Information")
        request.setDescription("Downloading...")
  
        request.setDestinationInExternalFilesDir(this,"CI","CustomerInformation.apk")
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
        val manager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
        isDownloaded = manager.enqueue(request)
        val broadcast = object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                val id = intent?.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,-1)
                if (id == isDownloaded) {
                    val install = Intent(Intent.ACTION_VIEW);
                    install.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP;
                    val uri  = ? // dont know how to get path of where file is downloaded
                    install.setDataAndType(Uri.parse(uri), manager.getMimeTypeForDownloadedFile(isDownloaded));
                    startActivity(install);
                    unregisterReceiver(this);
                    finish()
                }
            }
        }
        registerReceiver(broadcast, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE))
    }

我不知道我在“override onReceive()”中使用的代码是否会打开并安装 apk 文件...任何建议如何打开下载的 APK 文件来安装它?请

标签: androidbroadcastreceiverapkuriandroid-download-manager

解决方案


推荐阅读