Android 6.0 – 外部存储文件在应用卸载时被删除

我的应用程序使用DownloadManager将文件下载到设备的“音乐”文件夹的子目录.
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
...
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC) + "/MyStuff/song.mp3");
request.setDestinationUri(Uri.fromFile(file));

我注意到,当从运行Marshmallow的设备卸载该应用程序时,这些文件将被删除(这在旧的操作系统版本上不会发生).
你有什么想法吗?

谢谢

解决方法

这是通过名为 DownloadReceiver的内部类完成的,并在com.android.providers.downloads package manifest中定义
<receiver android:name=".DownloadReceiver" android:exported="false">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        <action android:name="android.intent.action.UID_REMOVED" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.MEDIA_MOUNTED" />
        <data android:scheme="file" />
    </intent-filter>
</receiver>

这里的android.intent.action.UID_REMOVED动作抓住眼睛.它在Lollipop中引入,触发对handleUidRemoved()执行的调用

resolver.delete(ALL_DOWNLOADS_CONTENT_URI,Constants.UID + "=" + uid,null);

相关文章

Android 如何解决dialog弹出时无法捕捉Activity的back事件 在...
Android实现自定义带文字和图片的Button 在Android开发中经常...
Android 关于长按back键退出应用程序的实现最近在做一个Andr...
android自带的时间选择器只能精确到分,但是对于某些应用要求...