Question

I need to install an apk file programmatically. Following this post 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?

Here is my 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)) > 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<String, String, String> {

    /**
     * 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);







    }

}
  }
Was it helpful?

Solution

please use follwing code

       public void Update(String apkurl){
  try {
        URL url = new URL(apkurl);
        HttpURLConnection c = (HttpURLConnection) url.openConnection();
        c.setRequestMethod("GET");

        c.connect();

        String PATH = Environment.getExternalStorageDirectory() + "/download/";
        File file = new File(PATH);
        file.mkdirs();
        File outputFile = new File(file, "app.apk");
        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();//till here, it works fine - .apk is download to my sdcard in download file

        Intent promptInstall = new Intent(Intent.ACTION_VIEW)
        .setData(Uri.parse(PATH+"app.apk"))
        .setType("application/android.com.app");
        startActivity(promptInstall);//installation is not working

    } catch (IOException e) {
        Toast.makeText(getApplicationContext(), "Update error!", Toast.LENGTH_LONG).show();
    }
 }  

OTHER TIPS

After download the apk into sdcard call this method with apk path..

protected void installApp() {
        // TODO Auto-generated method stub
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(
                Uri.fromFile(new File(Environment.getExternalStorageDirectory()
                        + File.separator + "IHS_HIV.apk")),
                "application/vnd.android.package-archive");
        startActivity(intent);
        finish();
    }

Method to down load Apk from URL

protected void downloadFileFromUrl() {
        // TODO Auto-generated method stub

        try {

            progressBar.setProgress(progressBar.getMax() - 50);
            URL url = new URL(URL);
            URLConnection connection = url.openConnection();
            connection.connect();
            // this will be useful so that you can show a typical 0-100%
            // progress bar
            int fileLength = connection.getContentLength();
            File file = new File(Environment.getExternalStorageDirectory()
                    + File.separator + "IHS_HIV.apk");
            file.createNewFile();

            // download the file
            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream(
                    Environment.getExternalStorageDirectory() + File.separator
                            + "IHS_HIV.apk");

            byte data[] = new byte[1024];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                // publishProgress((int) (total * 100 / fileLength));

                progressBar.setProgress((int) (total * 100 / fileLength));
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();

        } catch (Exception e) {
            ErrorLog.setErrorMessage(getApplicationContext(), e);
            Log.e("File Creating Error", e.getMessage());
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top