Android11上无法写入外部存储
创始人
2024-08-20 11:30:13
0

从Android 11开始,外部存储的访问权限受到了限制,特别是在应用程序合规性方面。为了解决这个问题,应该向应用添加WRITE_EXTERNAL_STORAGE 权限并使用 MediaStore API 来写入外部存储。MediaStore API 可以允许应用将文件写入外部存储,并使文件与媒体库相关联。以下是一个例子:

if (Environment.isExternalStorageManager()) {
   // You can write the files to external storage now
} else {
   // Requesting the permission from the user
   Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
   Uri uri = Uri.fromParts("package", BuildConfig.APPLICATION_ID, null);
   intent.setData(uri);
   startActivity(intent);
}

上述代码首先检查应用是否被授予读取/写入外部存储权限,如果是,则可以直接写入外部存储。否则,需要请求用户授权来使用此API。

使用 MediaStore API 写入文件:

ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DISPLAY_NAME, "File Name");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
values.put(MediaStore.Images.Media.IS_PENDING, 1);

Uri collection = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
Uri item = getContentResolver().insert(collection, values);

try {
  OutputStream out = getContentResolver().openOutputStream(item);
  // Write the file to the stream
  out.close();
} catch (IOException e) {
  e.printStackTrace();
}

values.put(MediaStore.Images.Media.IS_PENDING, 0);
getContentResolver().update(item, values, null, null);

上述代码演示了如何使用 MediaStore API 写入图像文件。可以使用类似的方式写入不同类型的文件。

相关内容

热门资讯

黑科技插件(红龙扑克)poke... 黑科技插件(红龙扑克)pokerrrr2真是真的是有挂!太实锤了起初真的有挂(2025已更新)(哔哩...
黑科技工具(wepoke挂透视... poker world新手教程相关信息汇总(需添加指定威信136704302获取下载链接);黑科技工...
黑科技辅助挂(德州之星ai)w... 黑科技辅助挂(德州之星ai)wpk微扑克素来是真的有挂!太实锤了从前有挂(2023已更新)(哔哩哔哩...
黑科技辅助挂挂(新版Wepok... 黑科技辅助挂挂(新版Wepoke)德扑助手切实是真的有挂!太坑了先前是真的有挂(2025已更新)(哔...
黑科技数据(微扑克总结)AAP... 黑科技数据(微扑克总结)AAPOKeR原先是真的有挂!太实锤了往昔真的有挂(2023已更新)(哔哩哔...
黑科技了解(新版Wepoke)... 黑科技了解(新版Wepoke)AApoker固有是真的有挂!太实锤了原来真的是有挂(2020已更新)...
黑科技系统(德州微扑克专用)w... 黑科技系统(德州微扑克专用)wEpoKe竟然是有挂!太无语了好像真的有挂(2022已更新)(哔哩哔哩...
黑科技规律(最新版wpk)来玩... WePoker透视辅助版本解析‌,黑科技规律(最新版wpk)来玩app德州总是真的有挂!太离谱了最初...
黑科技辅助(智星德州)德州wp... 黑科技辅助(智星德州)德州wpk德州一向存在有挂!太无语了总是有挂(2025已更新)(哔哩哔哩)1、...
黑科技好牌(poker wor... 黑科技好牌(poker world外挂)来玩德州本来是真的有挂!太坑了总是真的有挂(2022已更新)...