简体   繁体   English

使用凌空下载并安装APK

[英]Downloading and installing an APK using volley

I'm tring to download an update over the web. 我想通过网络下载更新。 This is with the latest volley version. 这是最新的截击版本。 I'm using a Stringrequest at the moment. 我目前正在使用Stringrequest

class UpdateService : IntentService("Update Serivce") {
companion object {
    val VERSION_URL = "<version url>"
    val FILE_URL = "<apk url>"
    val LOG_TAG = "UPDATE"
    fun initialize(context: Context) = context.startService(Intent(context, UpdateService::class.java))
}

/**
 * Checks remote for an update
 */
override fun onHandleIntent(intent: Intent?) {
    Log.d(LOG_TAG, "Retrieving new version")
    // Get version number
    NetworkService().get(Uri.parse(VERSION_URL),
            Response.Listener { success(it) },
            Response.ErrorListener {
                Log.d(LOG_TAG, "Failed to update ${it.toString()}")
                FirebaseCrash.report(it)
            })
}

private fun success(it: String?) {
    Log.d(LOG_TAG, "Remote version: $it")
    Log.d(LOG_TAG, "Local version: ${BuildConfig.VERSION_NAME}")

    if (!it.equals(BuildConfig.VERSION_NAME)) {
        Log.d(LOG_TAG, "Fetching new update")
        NetworkService().get(
                Uri.parse(FILE_URL),
                Response.Listener { installUpdate(it) },
                Response.ErrorListener {
                    Log.d(LOG_TAG, "failed to get new APK")
                    FirebaseCrash.report(it)
                }
        )
    }
}

private fun installUpdate(it: String) {
    Log.d(LOG_TAG, "retrieved update")

    val file = File(this.externalCacheDir, "update.apk")

    if(!file.exists()){
        file.createNewFile()
    }

    file.writeBytes(it.toByteArray())

    val intent = Intent(Intent.ACTION_VIEW)
    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive")
    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK

    Log.d(LOG_TAG, "Installing")

    startActivity(intent)
}

} }

When launching the installing activity, I will get a parse error from android. 启动安装活动时,我将收到android的解析错误。

无法解析

How can I download and save the file as an usable APK with volley? 如何通过凌空下载并将文件另存为可用的APK?

The issue is with the directories. 问题出在目录上。 I tried writing to a cache directory, and installing from there. 我尝试写入缓存目录,然后从那里安装。 Change the directory to context.getExternalFilesDir(<Appname>, "update.apk") and it will install without a problem. 将目录更改为context.getExternalFilesDir(<Appname>, "update.apk") ,它将成功安装。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM