2

我正在使用以下程序下载并安装 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);
}
4

1 回答 1

2

您可以注册一个广播接收器,它会在安装完成时通知您,届时您可以触发代码以删除 apk。

请看这个问题

如何知道安装何时完成

于 2013-09-24T04:22:29.577 回答