部分用户反馈华为手机(P30,Mate20等)在分享文件时报错:Failed to find configured root that contains /storage/emulated/0/...。但是公司自己的测试机又不会出现问题。经过一番摸索解决方案如下:
private static final String HUAWEI_MANUFACTURER = "Huawei";
public static Uri getUriForFile(Context context, File file) {
String authority = context.getPackageName() + ".fileprovider";
if (Build.VERSION.SDK_INT >= 24) {
if (HUAWEI_MANUFACTURER.equalsIgnoreCase(Build.MANUFACTURER)) {
try {
return FileProvider.getUriForFile(context, authority, file);
} catch (IllegalArgumentException e) {
final File cacheFolder = new File(context.getCacheDir(), HUAWEI_MANUFACTURER);
if (!cacheFolder.exists()) cacheFolder.mkdirs();
final File cacheLocation = new File(cacheFolder, file.getName());
if (cacheLocation.exists()) cacheLocation.delete();
try {
FileHelps.copy(file.getAbsolutePath(), cacheLocation.getAbsolutePath());
return FileProvider.getUriForFile(context, authority, cacheLocation);
} catch (Exception e1) {
throw new IllegalArgumentException("Huawei devices are unsupported for Android N", e1);
}
}
} else {
return FileProvider.getUriForFile(context, authority, file);
}
} else {
return Uri.fromFile(file);
}
}
public class FileHelps {
//文件拷贝
public static boolean copy(String fromFile, String toFile) {
InputStream fosfrom = null;
OutputStream fosto = null;
try {
fosfrom = new FileInputStream(fromFile);
fosto = new FileOutputStream(toFile);
byte[] bt = new byte[1024];
int c;
while ((c = fosfrom.read(bt)) > 0) {
fosto.write(bt, 0, c);
}
fosfrom.close();
fosto.close();
return true;
} catch (Exception ex) {
if (fosfrom != null) {
try {
fosfrom.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fosto != null) {
try {
fosto.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path name="public-files-path" path="." />
<cache-path name="private-cache-path" path="." />
</paths>
已经过检测,可以分享成功
|