Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private class DownloadTask extends AsyncTask<String, Void, Void> {
- private File PATH;
- private File file;
- // make sure you change Main to your activity name.
- private final ProgressDialog dialog = new ProgressDialog(Main.this);
- @Override
- protected Void doInBackground(String... params) {
- // TODO Auto-generated method stub
- HttpPost httppost = new HttpPost(updateURL);
- HttpClient httpclient = new DefaultHttpClient();
- try {
- // Execute HTTP Post Request
- HttpResponse response = httpclient.execute(httppost);
- StatusLine statusLine = response.getStatusLine();
- int responseCode = statusLine.getStatusCode();
- InputStream in;
- HttpEntity entity;
- if (responseCode == 200) {
- entity = response.getEntity();
- in = entity.getContent();
- if (android.os.Environment.getExternalStorageState()
- .equals(android.os.Environment.MEDIA_MOUNTED))
- PATH = new File(
- android.os.Environment
- .getExternalStorageDirectory(),
- "android/data/com.example.app/cache/");
- else
- PATH = getApplicationContext().getCacheDir();
- if (!PATH.exists())
- PATH.mkdirs();
- file = new File(PATH, "MyUpdate.apk");
- OutputStream os = new FileOutputStream(file);
- // this function is from Fedor's Utils class in his lazy list demo, posted at:
- // http://stackoverflow.com/questions/541966/android-how-do-i-do-a-lazy-load-of-images-in-listview
- CopyStream(in, os);
- os.close();
- }
- } catch (ClientProtocolException e) {
- // TODO Auto-generated catch block
- } catch (IOException e) {
- // TODO Auto-generated catch block
- }
- return null;
- }
- @Override
- protected void onPostExecute(final Void unused) {
- if (update) {
- Intent intent = new Intent();
- Uri uri = Uri.fromFile(file);
- intent.setAction(android.content.Intent.ACTION_VIEW);
- intent.setDataAndType(Uri.parse(uri.toString()),
- "application/vnd.android.package-archive");
- startActivity(intent);
- dialog.dismiss();
- }
- }
- @Override
- protected void onPreExecute() {
- this.dialog.setMessage("Downloading...");
- this.dialog.show();
- }
- }
- public static void CopyStream(InputStream is, OutputStream os) {
- final int buffer_size = 1024;
- try {
- byte[] bytes = new byte[buffer_size];
- for (;;) {
- int count = is.read(bytes, 0, buffer_size);
- if (count == -1)
- break;
- os.write(bytes, 0, count);
- }
- } catch (Exception ex) {
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment