Android Q分区存储下如何创建及删除可被MmsManager访问的公共文件
最优解决方案:使用FileProvider共享应用私有目录文件
这个方案完全不需要申请任何存储权限,临时文件仅存在于你的应用私有目录,发送完成后可直接删除,也不会污染用户的公共存储空间,是Android官方推荐的跨应用文件共享方式。
具体实现步骤
- 配置FileProvider
在AndroidManifest.xml中添加provider声明:
<provider android:name="androidx.core.content.FileProvider" android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths" /> </provider>
- 配置共享目录路径
在res/xml目录下新建provider_paths.xml文件,配置用于存放彩信PDU临时文件的目录:
<?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <files-path name="mms_temp" path="mms_pdu/" /> </paths>
这里配置的是应用内部私有存储的files/mms_pdu/目录作为共享目录。
3. 编写文件创建、授权、删除逻辑
// 创建私有目录下的临时文件 File pduDir = new File(mContext.getFilesDir(), "mms_pdu"); if (!pduDir.exists()) pduDir.mkdirs(); String fileName = "send." + String.valueOf(Math.abs(mRandom.nextLong())) + ".dat"; File pduFile = new File(pduDir, fileName); // 写入pdu数据 try (FileOutputStream writer = new FileOutputStream(pduFile)) { writer.write(pdu); } catch (IOException e) { Log.e(TAG, "Error writing PDU file", e); } // 获取FileProvider生成的共享URI Uri contentUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileprovider", pduFile); // 给MmsService授予临时读权限 mContext.grantUriPermission("com.android.mms", contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION); // 此处调用MmsManager发送彩信,传入上面的contentUri即可 // 发送完成后直接删除文件,无需任何权限 pduFile.delete();
如果你坚持使用MediaStore方案
你自己的应用通过contentResolver.insert写入MediaStore的文件,在Android 10及以上系统默认就拥有该文件的删除权限,不需要申请任何额外权限,直接调用以下代码即可删除:
contentResolver.delete(contentUri, null, null);
如果删除失败,检查你是不是重建了应用进程、或者升级了应用版本导致签名变更,这两种情况会丢失原有MediaStore文件的所有权,需要提前处理。
内容的提问来源于stack exchange,提问作者sidetrail
相关产品推荐
相关产品推荐

