2016-09-20 48 views
0

我正在通过网络下载更新。这是最新的排球版本。目前我正在使用Stringrequest使用volley下载和安装APK

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) 
} 

}

当启动安装活动,我会从安卓得到一个解析错误。

can't parse

如何下载和文件保存为一个凌空使用APK?

+0

检查apk的最低版本和您的手机vesrion – PriyankaChauhan

+0

我真的使用相同的设备,因为我用于开发。这不是问题。 – Samyn

+0

它是已签名的apk吗?您是否启用了“未知资源”设置?在某些情况下,如果apk文件未被正确/完全下载,则可能会发生此错误。 –

回答

0

问题出在目录上。我试图写入一个缓存目录,并从那里安装。将目录更改为context.getExternalFilesDir(<Appname>, "update.apk"),它将安装而不会出现问题。