android.os.FileUriExposedException:在 android.os.StrictMode.onFileUriExposed

android.os.FileUriExposedException: at android.os.StrictMode.onFileUriExposed

我正在关注 this tutorial 使用 FileProvider 而不是 Uri.FromFile() 但我不确定如何在我的服务中使用 FileProvider。

FileProvider.getUriForFile() 需要第一个参数的上下文,但因为我在我的服务中使用它,所以我没有 activity 上下文。

我该怎么办?

我需要改变这个:

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)

代码片段:

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();
        }

    }

What am I supposed to do?

Service 是一个 Context。因此,如果您直接在 Service 中调用 getUriForFile(),请将 this 用于 Context

行内:

 Uri swatchImageUri = FileProvider.getUriForFile(//,
                    BuildConfig.APPLICATION_ID + ".provider",
                    swatchImageFile);

将 activity 作为第一个参数传递:

 Uri swatchImageUri = FileProvider.getUriForFile(activity,
                BuildConfig.APPLICATION_ID + ".provider",
                swatchImageFile);