Android:通过内容 uri 删除文件

Twi*_*dek 2 android delete-file android-contentprovider

我的应用程序能够打开和处理某些文件。因此,您可以在文件管理器中点击这样的文件,我的应用程序将被提供来打开它。清单文件中的意图过滤器的设置如下。

<intent-filter>
  <action android:name="android.intent.action.VIEW" />

  <category android:name="android.intent.category.DEFAULT" />
  <category android:name="android.intent.category.BROWSABLE" />

  <data android:mimeType="text/plain" />
</intent-filter>
Run Code Online (Sandbox Code Playgroud)

像这样读取和处理文件效果很好:

Context.getContentResolver().openInputStream(getIntent().getData());
Run Code Online (Sandbox Code Playgroud)

问题是,我想在处理后删除该文件。(如果用户选中该文件的复选框)用户通常在使用我的应用程序打开该文件后不再需要该文件。

目前,只有当文件作为文件 uri(以 file:// 开头)提供给我时,我才能执行此操作。在这种情况下,这段代码可以正常工作:

new File(contentUri.getPath()).delete();
Run Code Online (Sandbox Code Playgroud)

但如果该文件作为内容 uri 提供,我不知道如何删除该文件。(以内容://开头)

例如,返回 null,并且不执行任何操作:

Context.getContentResolver().delete(getIntent().getData(), null, null);
Run Code Online (Sandbox Code Playgroud)

Tan*_*yan 5

我已经使用下面的代码解决了这个问题。

DocumentFile.fromSingleUri(getApplicationContext(),fileUri ).delete();

这很好用。尝试一下。