Android How to - Download and Install APK








Question

We would like to know how to download and Install APK.

Answer

/*  w ww.j  ava2  s .  c o  m*/
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;

class APK {

  public static boolean downloadFile(Context context, String address,
      String filename) {
    return downloadAPK(context, address, filename, false);
  }

  public static boolean downloadAPK(Context context, String address,
      String filename, boolean install) {
    try {
      String PATH = Environment.getExternalStorageDirectory() + "/download/";
      File file = new File(PATH);
      file.mkdirs();

      URL url = new URL(address);
      HttpURLConnection c = (HttpURLConnection) url.openConnection();
      c.setRequestMethod("GET");
      c.setDoOutput(true);
      c.connect();

      File outputFile = new File(file, filename);
      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();

      if (install) {
        return installAPK(
            context,
            Uri.fromFile(new File(Environment.getExternalStorageDirectory()
                + "/download/" + filename)));
      } else {
        return true;
      }
    } catch (IOException e) {

      return false;
    }
  }
  public static boolean installAPK(Context context, Uri filename) {
    try {
      Intent intent = new Intent(Intent.ACTION_VIEW);
      intent
          .setDataAndType(filename, "application/vnd.android.package-archive");
      intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      context.startActivity(intent);

      return true;
    } catch (Exception e) {
      return false;
    }
  }
}