【发布时间】:2019-07-24 13:36:44
【问题描述】:
我正在关注 this tutorial 使用 FileProvider 而不是 Uri.FromFile() 但我不确定如何在我的服务中使用 FileProvider。
FileProvider.getUriForFile() 需要第一个参数的上下文,但因为我在我的服务中使用它,所以我没有活动上下文。
我该怎么办?
我需要改变这个:
Uri swatchImageUri = Uri.fromFile(favoritesImageFile);
根据他们上面的建议。
这是我在不使用 FileProvider 的情况下遇到的当前异常:
2019-07-23 23:04:42.748 11034-11034/com.company.projname E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.company.projname, PID: 11034
android.os.FileUriExposedException: file:///storage/emulated/0/Android/data/com.company.projname/cache/colors.png exposed beyond app through ClipData.Item.getUri()
at android.os.StrictMode.onFileUriExposed(StrictMode.java:1978)
at android.net.Uri.checkFileUriExposed(Uri.java:2371)
at android.content.ClipData.prepareToLeaveProcess(ClipData.java:963)
at android.content.Intent.prepareToLeaveProcess(Intent.java:10216)
at android.content.Intent.prepareToLeaveProcess(Intent.java:10222)
at android.content.Intent.prepareToLeaveProcess(Intent.java:10201)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1667)
at android.app.Activity.startActivityForResult(Activity.java:4586)
代码sn-p:
public void shareColorSwatch(SwatchViewModel model){
try {
String swatchName = model.First.get().Name.get().replaceAll("\\s","").replaceAll("'", "") + "_" +
model.Second.get().Name.get().replaceAll("\\s","").replaceAll("'", "") + "_" +
model.Third.get().Name.get().replaceAll("\\s","").replaceAll("'", "");
Display display = activity.getWindowManager().getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
Bitmap swatchBitmap = createColorSwatchBitmap(model, screenWidth, screenHeight);
String fileName = String.format("swatch_%s.png", swatchName);
File swatchImageFile = getImageFile(activity,fileName, swatchBitmap, true);
Uri swatchImageUri = FileProvider.getUriForFile(//,
BuildConfig.APPLICATION_ID + ".provider",
swatchImageFile);
//Uri swatchImageUri = Uri.fromFile(swatchImageFile);
shareImage(activity,swatchName,swatchImageUri);
}catch (Exception e)
{
e.printStackTrace();
}
}
【问题讨论】:
-
你能把你的服务代码粘贴到你调用方法的地方吗?
-
@JuanDanielOrnella 已发布。哦,我只是想它应该只是上面的活动?
标签: java android android-fileprovider