Android4.4下MediaProvider无法向外置SD卡中文件写数据的解决方法

Android4.4下MediaProvider无法向外置SD卡中文件写数据的解决方法,第1张

概述本文实例讲述了Android4.4下MediaProvider无法向外置SD卡中文件数据的解决方法。分享给大家供大家参考,具体如下:

本文实例讲述了AndroID4.4下MediaProvIDer无法向外置SD卡中文件写数据的解决方法。分享给大家供大家参考,具体如下:

AndroID4.4平台限制应用对外置SD卡的读写权限。MediaProvIDer通过 checkAccess方法 限制对外置SD卡的读写。

private voID checkAccess(Uri uri,file file,int modeBits) throws fileNotFoundException {  final boolean isWrite = (modeBits & MODE_WRITE_ONLY) != 0;  final String path;  try {   path = file.getCanonicalPath();  } catch (IOException e) {   throw new IllegalArgumentException("Unable to resolve canonical path for " + file,e);  }  Context c = getContext();  boolean readGranted =    (c.checkCallingOrSelfUriPermission(uri,Intent.FLAG_GRANT_READ_URI_PERMISSION)    == PackageManager.PERMISSION_GRANTED);  if (path.startsWith(sExternalPath) || path.startsWith(sLegacyPath)) {   if (!readGranted) {    c.enforceCallingOrSelfPermission(      READ_EXTERNAL_STORAGE,"External path: " + path);   }   if (isWrite) {    if (c.checkCallingOrSelfUriPermission(uri,Intent.FLAG_GRANT_WRITE_URI_PERMISSION)      != PackageManager.PERMISSION_GRANTED) {     c.enforceCallingOrSelfPermission(       WRITE_EXTERNAL_STORAGE,"External path: " + path);    }   }  } else if (path.startsWith(sCachePath)) {   if (!readGranted) {    c.enforceCallingOrSelfPermission(      ACCESS_CACHE_fileSYstem,"Cache path: " + path);   }  //外置SD卡,isWrite = true  } else if (isWrite) {   // don't write to non-cache,non-sdcard files.   throw new fileNotFoundException("Can't access " + file);  } else if (isSecondaryExternalPath(path)) {   // read access is OK with the appropriate permission   if (!readGranted) {    c.enforceCallingOrSelfPermission(      READ_EXTERNAL_STORAGE,"External path: " + path);   }  } else {   checkWorldReadAccess(path);  }}

从以上代码我们看出,如果sExternalPath 没有指向外置SD卡并且path 是外置SD卡的文件路径,那么该方法 就会抛出fileNotFoundException,sExternalPath 一般都是指向内部存储

在应用中 我们通常 通过contentresolver.openOutputStream(uri) 来打开存储卡上媒体文件的文件流,如果媒体文件在外置SD卡上,那么我们就无法打开对应的文件流,自然肯定无法向其中写数据。

为了解决该问题,我们只能改变AndroID4.4平台下MediaprovIDer 对向SD卡写数据的限制,具体修改方式如下

private voID checkAccess(Uri uri,Intent.FLAG_GRANT_READ_URI_PERMISSION)    == PackageManager.PERMISSION_GRANTED);  if (path.startsWith(sExternalPath) || path.startsWith(sLegacyPath) || isSecondaryExternalPath(path)) {   if (!readGranted) {    c.enforceCallingOrSelfPermission(      READ_EXTERNAL_STORAGE,non-sdcard files.   throw new fileNotFoundException("Can't access " + file);  } else {   checkWorldReadAccess(path);  }},

对于满足isSecondaryExternalPath(path) 的文件路径,我们都可以进行读写,对于外置SD卡的文件而言 isSecondaryExternalPath(path) 肯定为true

希望本文所述对大家AndroID程序设计有所帮助。

总结

以上是内存溢出为你收集整理的Android4.4下MediaProvider无法向外置SD卡中文件写数据的解决方法全部内容,希望文章能够帮你解决Android4.4下MediaProvider无法向外置SD卡中文件写数据的解决方法所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/web/1142231.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-31
下一篇2022-05-31

发表评论

登录后才能评论

评论列表(0条)

    保存