Thursday, December 12, 2013

Code Snippet - Download and install apk file programmatically

Downloading a file can be done in many ways.

either using httpurlconnection or httpclient or download manager in android.

using httpurlconnection

String result = "";
try {
URL url = new URL(this.url);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();

File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "filename.apk");

FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();

byte[] buffer = new byte[1024];
int bufferLength = 0;

while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
result = "done";

catch (MalformedURLException e) {
e.printStackTrace();
catch (IOException e) {
e.printStackTrace();
}
return result;


using download manager works from api 9,

Uri src_uri = Uri.parse("http://your.url.here/File.apk");
Uri dst_uri = Uri.parse("file:///mnt/sdcard/download/File.apk");

DownloadManager.Request req = new DownloadManager.Request(src_uri);
req.setDestinationUri(dst_uri);
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(req);
There is another one line technique,
org.apache.commons.io.FileUtils.copyURLToFile(URL, File)

Below is an example,

class InstallTask extends AsyncTask<Void, Void, String> {
ProgressDialog mProgressDialog;

Context context;
String url;

public InstallTask(Context context, String url) {
this.context = context;

this.url = url;

}

protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(context,
"Download", " Downloading in progress..");
}

private String downloadapk() {
String result = "";
try {
URL url = new URL(this.url);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();

File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "filename.apk");

FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();

byte[] buffer = new byte[1024];
int bufferLength = 0;

while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
result = "done";

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}

protected String doInBackground(Void... params) {
String result = downloadapk();
return result;
}

protected void onPostExecute(String result) {
if (result.equals("done")) {
mProgressDialog.dismiss();
installApk();
} else {
Toast.makeText(context, "Error while downloading",
Toast.LENGTH_LONG).show();

}
}

private void installApk() {
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(new File("/sdcard/filename.apk"));
intent.setDataAndType(uri, "application/vnd.android.package-archive");
context.startActivity(intent);
}

}


just paste the above code to use it as an asynctask.

Make sure to add write external storage and internet permission.

You can add this code before calling installApk(), if you may want to check for corrupted/incomplete apk files.

private boolean isApkCorrupted() {
        boolean corruptedApkFile = false;
        try {
             new JarFile(new File("/sdcard/filename.apk"));
        } catch (Exception ex) {
             corruptedApkFile = true;
        }
        return corruptedApkFile;
    } 


Courtesy
http://bpsinghrajput.blogspot.in/2012/07/how-to-download-and-install-apk-from.html
http://gafurbabu.wordpress.com/2012/02/29/download-file-in-android-by-using-asynctask-in-background-operations/
http://stackoverflow.com/questions/11121121/android-download-an-application-using-the-downloadmanager-class
http://stackoverflow.com/questions/8338786/is-there-a-way-to-be-notified-when-apk-fails-to-being-installed

1 comment:

  1. hi sir, i have an android app in own server not in google playstore, my clients are using my app, if any big fix or updates are available i want to notify my clients application and update it. Programmatically how to do it... plz help me

    ReplyDelete