簡體   English   中英

如何在android studio中遠程下載和安裝apk更新?

[英]How to download and install an apk update in android studio remotly?

如何在 Android 編程中下載和安裝 apk 文件。 我需要從包含我的 apk 文件的 URL 下載並安裝新更新...通常的過程是檢查是否有新版本,然后下載並安裝它。

這是我現在使用的代碼:

    val extStorageDirectory = Environment.getExternalStorageDirectory().toString()
        val folder = File(extStorageDirectory)
        Log.e("extStorageDirectory", extStorageDirectory)
        folder.mkdir()
        val file = File(folder, "AppName." + "apk")
        try {
            file.createNewFile()
            /**
             * APKURL is your apk file url(server url)
             */
            DownloadFile(apkLink, file)
        } catch (e1: IOException) {
//            e1.printStackTrace()
            Log.e("e1", e1.toString())
        }


    private fun DownloadFile(fileURL: String, directory: File) {

        try {
            val f = FileOutputStream(directory)
            val u = URL(fileURL)
            val c = u.openConnection() as HttpURLConnection
            c.requestMethod = "GET"
            //c.setDoOutput(true);
            c.connect()
            val `in` = c.inputStream
            val buffer = ByteArray(1024)
            var len1 = 0
            while (`in`.read(buffer).also { len1 = it } > 0) {
                f.write(buffer, 0, len1)
            }
            f.close()

            val intent = Intent(Intent.ACTION_VIEW)
            intent.setDataAndType(
                Uri.fromFile(
                    File(
                        Environment.getExternalStorageDirectory()
                            .toString()  + "AppName.apk"
                    )
                ), "application/vnd.android.package-archive"
            )
            startActivity(intent)

        } catch (e: Exception) {
            println("exception in DownloadFile: --------$e")
            e.printStackTrace()
            Log.e("exception in DownloadFile", e.toString())
        }
    }

我收到此錯誤:java.io.IOException: Operation not allowed

在您的設備中,轉到設置 -> 安全 -> 未知來源 -> 允許從未知來源安裝應用程序。 因為您沒有使用 CHplay,所以您必須接受來自其他來源的 apk

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM