2016-09-20 114 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"),它將安裝而不會出現問題。