如何在安装后删除.apk

时间:2013-09-24 04:16:36

标签: android android-sdcard apk

我使用以下程序下载并安装apk。成功安装后如何从sdcard中删除apk?我试过的是:

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

但它会在安装前删除该文件。

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);
}

1 个答案:

答案 0 :(得分:2)

您可以注册一个广播接收器,该接收器将在安装完成时通知您,此时您可以激活您的代码以进行删除apk。

请看这个问题

How to find out when an installation is completed