安卓应用自更新

12

可能重复问题:
Android:以编程方式安装.apk文件

我需要更新我的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
1个回答

18

如果更新的 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);

2
嗨@lexmiir,感谢回复,我按照您说的做了,现在我得到了一个警告对话框,上面写着解析器错误-存在解析包的问题。有什么线索吗? :-) - nonickh
嗨@nonickh,你是否使用相同的密钥签署了两个apk?当具有相同包名的应用程序使用不同的密钥签署时,可能会出现此错误。 - Alexei
嗨@lexmiir,抱歉回复晚了,我比较了这两个文件,它们是不同的,可能是由于复制网站的过程引起的。我会尝试解决这个问题,感谢您的支持。 - nonickh
1
可能已经解决了,但是为了以后的参考,您不应该写入整个缓冲区,而只应该写入读取的字节数,例如 fos.write(buff, 0, len),其中 len 在最后一块被写入时可能小于 buffer.length - David O'Meara
我遇到了同样的错误,并通过在FTP程序中使用二进制模式上传APK文件来解决它。 - 2red13

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接