使用凌空下载和安装APK

时间:2016-09-20 08:28:39

标签: java android apk android-volley kotlin

我想通过网络下载更新。这是最新的凌空版本。我目前正在使用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)
}

}

启动安装活动时,我将从android获得解析错误。

can't parse

如何下​​载文件并将其保存为可用的APK并使用排球?

1 个答案:

答案 0 :(得分:0)

问题在于目录。我尝试写入缓存目录,然后从那里安装。将目录更改为context.getExternalFilesDir(<Appname>, "update.apk"),它将安装没有问题。