2

I am using the following program to download and install an apk. How can I remove the apk from the sdcard after successful installation? What I tried is:

File file = new File("/sdcard/filename.apk");
boolean deleted = file.delete();

But it will delete the file before installation.

protected Boolean doInBackground(String... arg0) {
  try {
    URL url = new URL( weburl +"username="+usename+"&password="+usepass +"&apk="+apk);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestMethod("GET");
    urlConnection.setDoOutput(true);
    urlConnection.connect();

    File sdcard = Environment.getExternalStorageDirectory();
    File file = new File(sdcard, "filename.apk");

    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();
    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri uri = Uri.fromFile(new File("/sdcard/filename.apk"));
    intent.setDataAndType(uri, "application/vnd.android.package-archive");
    startActivity(intent);

  } catch (MalformedURLException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  }
  return null;
}

private void installApk(){
  Intent intent = new Intent(Intent.ACTION_VIEW);
  Uri uri = Uri.fromFile(new File("/sdcard/filename.apk"));
  intent.setDataAndType(uri, "application/vnd.android.package-archive");
  startActivity(intent);
}
JScoobyCed
  • 10,203
  • 6
  • 34
  • 58
DKV
  • 1,767
  • 3
  • 28
  • 49
  • possible duplicate of [How to find out when an installation is completed](http://stackoverflow.com/questions/5176645/how-to-find-out-when-an-installation-is-completed) – flx Sep 24 '13 at 04:48
  • 1
    possible duplicate of [Delete an application (\*.apk) after installation](http://stackoverflow.com/questions/15984546/delete-an-application-apk-after-installation) – Gokul Nath KP Oct 09 '13 at 09:35

1 Answers1

2

You can register a broadcast receiver that will notify you when installation will complete and at that time you can fire your code for delete apk.

please see this question

How to find out when an installation is completed

Community
  • 1
  • 1
Jignesh Ansodariya
  • 12,583
  • 24
  • 81
  • 113