Download and install apk files from app in Android

For the purposes of simple download of file from app, I wrote the following function:

private void Download (String url, String packageName) {
	 		int count;
 	        try {
 	            java.net.URL url1 = new java.net.URL(url);
 	            URLConnection conexion = url1.openConnection();
 	            conexion.connect();
 	            // this will be useful so that you can show a tipical 0-100% progress bar
 	            int lenghtOfFile = conexion.getContentLength();
 	            //check directory
 	           File sdCard = Environment.getExternalStorageDirectory();
 	          File root = new File (sdCard.getAbsolutePath() + "/myLocation");
 	     		if (!root.exists()) {
 	              root.mkdirs();
 	          }
 	            // download the file
 	            InputStream input = new BufferedInputStream(url1.openStream());
 	            OutputStream output = new FileOutputStream(root.toString()+"/"+packageName+".apk");

 	            byte data[] = new byte[1024];

 	            long total = 0;

 	            while ((count = input.read(data)) != -1) {
 	                total += count;
 	                // publishing the progress....
 	                //publishProgress((int)(total*100/lenghtOfFile));
 	                output.write(data, 0, count);
 	            }

 	            output.flush();
 	            output.close();
 	            input.close();
 	        } catch (Exception e) {}
 	       Intent intent = new Intent(Intent.ACTION_VIEW);
 	       intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/myLocation/" +packageName+".apk")), "application/vnd.android.package-archive");
 	       startActivity(intent);  
	 	}

Syntax is very simple – just provide URL and package name, how to save.

2 comments

  1. просто word-wrap не помог, пришлось еще и ширину фиксировать

Leave a Reply

%d bloggers like this: