2012-01-28 85 views
7

可能重複:
Android: install .apk programmaticallyAndroid應用程序的自我更新

我需要更新我的Android應用程序。在程序的內部,我下載了新版本。我怎樣才能替換當前版本的下載(以編程方式)?

URL url = new URL("http://www.mySite.com/myFolder/myApp.apk"); 
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
try 
{ 
    FileOutputStream fos = this.getApplicationContext().openFileOutput("myApp.apk", Context.MODE_WORLD_READABLE|Context.MODE_WORLD_WRITEABLE); 

    InputStream in = new BufferedInputStream(urlConnection.getInputStream()); 
    BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8")); 

    StringBuilder sb = new StringBuilder(); 

    byte[] buffer = new byte[8192]; 
    int len; 
    while ((len = in.read(buffer)) != -1) 
    { 
     // EDIT - only write the bytes that have been written to 
     // the buffer, not the whole buffer 
     fos.write(buffer, 0, len); // file to save app 
    } 
    fos.close(); 

    ....  here I have the file of new app, now I need use it 

回答

11

如果更新後的APK具有相同的包名,並與你只需發送一個意圖,這將調用默認的Android安裝相同的密鑰簽名。已安裝的apk將被覆蓋。

Intent intent = new Intent(Intent.ACTION_VIEW); 
Uri uri = Uri.fromFile(new File(pathToApk)); 
intent.setDataAndType(uri, "application/vnd.android.package-archive"); 
startActivity(intent); 
+0

您好@lexmiir,感謝您的回覆,我做了你所說的,現在我得到了一個警告對話框說Parser錯誤 - 解析軟件包時出現問題。任何線索? :-) – nonickh 2012-01-28 20:02:18

+0

嗨@nonickh,你是否用相同的密鑰簽署了兩個apk?當具有相同包名的應用程序使用不同的密鑰簽名時,可能會出現此錯誤 – lexmiir 2012-01-28 20:52:28

+0

Hi @lexmiir,對於延遲,我比較了兩個文件,他們不同,可能是由複製站點的過程造成的,我首先嚐試爲了解決這個問題,感謝您的支持 – nonickh 2012-01-31 11:00:33