title: How to delete the .apk after installation
body: <p>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:</p>
  
  <pre><code>File file = new File("/sdcard/filename.apk");
  boolean deleted = file.delete();
  </code></pre>
  
  <p>But it will delete the file before installation.</p>
  
  <pre><code>protected Boolean doInBackground(String... arg0) {
    try {
      URL url = new URL( weburl +"username="+usename+"&amp;password="+usepass +"&amp;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)) &gt; 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);
  }
  </code></pre>