12

Possible Duplicate:
Android: install .apk programmatically

I need to update my android application. Internally the program, I download the new version. How can I replace the current version by that new was downloaded (programmatically)?

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
Community
  • 1
  • 1
nonickh
  • 229
  • 1
  • 3
  • 9

1 Answers1

17

If the updated apk has the same package name and is signed with the same key you can just send a intent which will call a default android installer. The installed apk will be overriden.

Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(new File(pathToApk));
intent.setDataAndType(uri, "application/vnd.android.package-archive");
startActivity(intent);
Alexei
  • 1,028
  • 1
  • 11
  • 17
  • 2
    Hi @lexmiir, thanks for reply, I do what you said and now I got an alert dialog saying Parser Error - There is a problem parsing the package. Any clues? :-) – nonickh Jan 28 '12 at 20:02
  • Hi @nonickh, did you signed both apk's with the same key? This error may appear when the applications with the same package name are signed with different keys – Alexei Jan 28 '12 at 20:52
  • Hi @lexmiir, Sorry for the delay, I compared the two files and they are different, probably caused by the process of copying the site, I first try to resolve this problem, grateful for your support – nonickh Jan 31 '12 at 11:00
  • 1
    probably already resolved, but for future reference you should not write the full buffer, only the number of bytes read ie `fos.write(buff, 0, len)` where `len` will probably be less than `buffer.length` when the last chunk is written. – David O'Meara Jul 03 '12 at 04:59
  • I had the same error and solved it by uploading the apk file by using binary mode in the ftp program. – 2red13 Jul 03 '12 at 06:18