Skip to content

Instantly share code, notes, and snippets.

@lifuzu
Created April 3, 2014 17:10
Show Gist options
  • Star 50 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
  • Save lifuzu/9958640 to your computer and use it in GitHub Desktop.
Save lifuzu/9958640 to your computer and use it in GitHub Desktop.
Android auto update apk implementation
public class UpdateApp extends AsyncTask<String,Void,Void>{
private Context context;
public void setContext(Context contextf){
    context = contextf;
}

@Override
protected Void doInBackground(String... arg0) {
      try {
            URL url = new URL(arg0[0]);
            HttpURLConnection c = (HttpURLConnection) url.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            String PATH = "/mnt/sdcard/Download/";
            File file = new File(PATH);
            file.mkdirs();
            File outputFile = new File(file, "update.apk");
            if(outputFile.exists()){
                outputFile.delete();
            }
            FileOutputStream fos = new FileOutputStream(outputFile);

            InputStream is = c.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len1);
            }
            fos.close();
            is.close();

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(new File("/mnt/sdcard/Download/update.apk")), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // without this flag android returned a intent error!
            context.startActivity(intent);


        } catch (Exception e) {
            Log.e("UpdateAPP", "Update error! " + e.getMessage());
        }
    return null;
}}

To use it, in your main activity call by this way:

            atualizaApp = new UpdateApp();
            atualizaApp.setContext(getApplicationContext());
            atualizaApp.execute("http://serverurl/appfile.apk");
Intent promptInstall = new Intent(Intent.ACTION_VIEW)
    .setDataAndType(Uri.parse("file:///path/to/your.apk"), 
                    "application/vnd.android.package-archive");
startActivity(promptInstall); 
Intent goToMarket = new Intent(Intent.ACTION_VIEW)
    .setData(Uri.parse("market://details?id=com.package.name"));
startActivity(goToMarket);

###References:

  1. http://stackoverflow.com/questions/4967669/android-install-apk-programmatically
  2. http://stackoverflow.com/questions/4604239/install-application-programmatically-on-android
@KaranSachrani
Copy link

App not installed
The package conflicts with an existing package by the same name

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment