猿问

使用文件提供程序检索内容 URI 失败

我花了几天时间阅读文档并遵循各种教程,但无论我做什么,我都会遇到错误。我正在尝试将图像保存在内部存储中,然后将其转换为内容 Uri,以便我可以使用系统裁剪和调整大小功能。如果有人能发现我的代码哪里有问题,我将不胜感激:


主要活动:


new Thread(() -> {

try {

    String temp = "temp";


    //Convert bitmap to byte array

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);

    byte[] bitmapData = bos.toByteArray();


    //Write the bytes in file

    FileOutputStream fos = openFileOutput(temp, MODE_PRIVATE);

    fos.write(bitmapData);

    fos.flush();

    fos.close();


    //onvert file to contentUri

    File file = new File(getFilesDir(), temp);


    Intent intent = new Intent();

    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

    Uri imageUri = FileProvider.getUriForFile(MainActivity.this, "@string/file_provider_authority", file);

    intent.setDataAndType(imageUri, "image/jpg");


    intent = WallpaperManager.getInstance(getApplicationContext()).getCropAndSetWallpaperIntent(imageUri);

    startActivityForResult(intent, ACTIVITY_CROP);


} catch (Exception e) {

    e.printStackTrace();

}

}).start();

显现:


<provider

        android:name="android.support.v4.content.FileProvider"

        android:authorities="@string/file_provider_authority"

        android:grantUriPermissions="true"

        android:exported="false">

        <meta-data

            android:name="android.support.FILE_PROVIDER_PATHS"

            android:resource="@xml/file_provider_paths" />

    </provider>

</application>

file_provider_paths.xml:


<paths>

<files-path

    path="/" name="temp" />

字符串.xml:


<resources>

<string name="file_provider_authority"

    translatable="false">com.me.wallpaper_app.provider

</string>



神不在的星期二
浏览 145回答 2
2回答

繁花如伊

"@string/file_provider_authority"不是您在 Java 中引用字符串资源的方式。使用getString(R.string.file_provider_authority)。更新:根据评论,第二个主要问题是此内容的使用者没有使用 的 MIME 类型Intent,而是调用getType()aContentResolver以从ContentProvider.&nbsp;在这种情况下,那是您的FileProvider,并且FileProvider只知道如何使用文件扩展名并将其转换为 MIME 类型。因此,usingtemp.jpeg提供FileProvider了返回正确 MIME 类型所需的信息。

慕斯王

尝试这个&nbsp; &nbsp; &nbsp; Uri imageUri = FileProvider.getUriForFile(MainActivity.this, R.string.file_provider_authority, file);也改变&nbsp; &nbsp; <paths>&nbsp; &nbsp; <files-path&nbsp; &nbsp; path="/" name="temp" />至&nbsp; &nbsp; <?xml version="1.0" encoding="utf-8"?>&nbsp; &nbsp; <paths xmlns:android="http://schemas.android.com/apk/res/android">&nbsp;&nbsp; &nbsp; <external-path name="external_files" path="."/>&nbsp; &nbsp; </paths>
随时随地看视频慕课网APP

相关分类

Java
我要回答