2012-01-28 120 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