title: Error in Installing apk programmatically from server
body: <p>I need to install an apk file programmatically. Following <a href="http://bpsinghrajput.blogspot.com/2012/07/how-to-download-and-install-apk-from.html" rel="nofollow">this post</a> I placed my apk file inside the root directory of my C: drive, but my application didn't install properly. How can I do this?</p>
  
  <p>Here is my code :</p>
  
  <pre><code>Button  button = (Button) findViewById(R.id.button1);
  
  button.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View arg0) {
          canWriteOnExternalStorage();
          downloadapk();
          installApk();
      }
  });
  
  private void downloadapk(){
      try {
          URL url = new URL("http://192.168.0.108/Root.apk");
          HttpURLConnection urlConnection = (HttpURLConnection) 
                                            url.openConnection();
          urlConnection.setRequestMethod("GET");
          urlConnection.setDoOutput(true);
          urlConnection.connect();
  
          File sdcard = Environment.getExternalStorageDirectory();
          File dir = new File(sdcard.getAbsolutePath() + "/nazeer/");
          dir.mkdirs();
          File file = new File(dir, "filename");
  
          FileOutputStream fileOutput = new FileOutputStream(file);
          InputStream inputStream = urlConnection.getInputStream();
  
          byte[] buffer = new byte[1024];
          int bufferLength = 0;
  
          while ( (bufferLength = inputStream.read(buffer)) &gt; 0 ) {
              fileOutput.write(buffer, 0, bufferLength);
          }
          fileOutput.close();
          //this.checkUnknownSourceEnability();
          //this.initiateInstallation();
      } catch (MalformedURLException e) {
              e.printStackTrace();
      } catch (IOException e) {
              e.printStackTrace();
      }
  }
  
  private void installApk(){
      Intent intent = new Intent(Intent.ACTION_VIEW);
  
      File sdcard = Environment.getExternalStorageDirectory();
      // to this path add a new directory path
      File dir = new File(sdcard.getAbsolutePath() + "/nazeer/");
  
      Uri uri = Uri.fromFile(dir);  
  
      intent.setDataAndType(uri, "application/vnd.android.package-archive");
      startActivity(intent);
  }
  
               after a lot of reserch finnaly i get solution using this sample code 
     http://www.androidhive.info/2012/04/android-downloading-file-by-showing-progress-bar/
  
  
  
  
  
  
  
  
  
  
  
  
  
          public class AndroidDownloadFileByProgressBarActivity extends Activity {
  
  // button to show progress dialog
  Button btnShowProgress;
  
  // Progress Dialog
  private ProgressDialog pDialog;
  ImageView my_image;
  // Progress dialog type (0 - for Horizontal progress bar)
  public static final int progress_bar_type = 0; 
  
  // File url to download
  private static String file_url = 
   "https://dl.dropboxusercontent.com/u/245131571/SampleApp.apk";
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
  
      // show progress bar button
      btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
      // Image view to show image after downloading
  //  my_image = (ImageView) findViewById(R.id.my_image);
      /**
       * Show Progress bar click event
       * */
      btnShowProgress.setOnClickListener(new View.OnClickListener() {
  
          @Override
          public void onClick(View v) {
              // starting new Async Task
              new DownloadFileFromURL().execute(file_url);
          }
      });
  }
  
  /**
   * Showing Dialog
   * */
  @Override
  protected Dialog onCreateDialog(int id) {
      switch (id) {
      case progress_bar_type:
          pDialog = new ProgressDialog(this);
          pDialog.setMessage("Downloading file. Please wait...");
          pDialog.setIndeterminate(false);
          pDialog.setMax(100);
          pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
          pDialog.setCancelable(true);
          pDialog.show();
          return pDialog;
      default:
          return null;
      }
  }
  
  /**
   * Background Async Task to download file
   * */
  class DownloadFileFromURL extends AsyncTask&lt;String, String, String&gt; {
  
      /**
       * Before starting background thread
       * Show Progress Bar Dialog
       * */
      @Override
      protected void onPreExecute() {
          super.onPreExecute();
          showDialog(progress_bar_type);
      }
  
      /**
       * Downloading file in background thread
       * */
      @Override
      protected String doInBackground(String... f_url) {
          int count;
          try {
              URL url = new URL(f_url[0]);
              URLConnection conection = url.openConnection();
              conection.connect();
              // getting file length
              int lenghtOfFile = conection.getContentLength();
  
              // input stream to read file - with 8k buffer
              InputStream input = new BufferedInputStream(url.openStream(), 8192);
  
              File file = new File(Environment.getExternalStorageDirectory() + 
         "/download2/");
              if (!file.exists()) {
                  file.mkdir();
              }
        //      file.mkdirs();
              File outputFile = new File(file, "app.apk");
        //      FileOutputStream fos = new FileOutputStream(outputFile);
  
              // Output stream to write file
      //        OutputStream output = new FileOutputStream("/sdcard/SampleApp.apk");
              OutputStream output = new FileOutputStream(outputFile);
  
              byte data[] = new byte[1024];
  
              long total = 0;
  
              while ((count = input.read(data)) != -1) {
                  total += count;
                  // publishing the progress....
                  // After this onProgressUpdate will be called
                  publishProgress(""+(int)((total*100)/lenghtOfFile));
  
                  // writing data to file
                  output.write(data, 0, count);
              }
  
              // flushing output
              output.flush();
  
              // closing streams
              output.close();
              input.close();
  
          } catch (Exception e) {
              Log.e("Error: ", e.getMessage());
          }
  
          return null;
      }
  
      /**
       * Updating progress bar
       * */
      protected void onProgressUpdate(String... progress) {
          // setting progress percentage
          pDialog.setProgress(Integer.parseInt(progress[0]));
     }
  
      /**
       * After completing background task
       * Dismiss the progress dialog
       * **/
      @Override
      protected void onPostExecute(String file_url) {
          // dismiss the dialog after the file was downloaded
          dismissDialog(progress_bar_type);
  
  
  
            Intent intent = new Intent(Intent.ACTION_VIEW);
  
                  intent.setDataAndType(Uri.fromFile(new   
  File(Environment.getExternalStorageDirectory() + "/download2/" + "app.apk")), 
    "application/vnd.android.package-archive");
                  intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                  startActivity(intent);
  
  
  
  
  
  
  
      }
  
  }
    }
  </code></pre>