ClipData.Item.getUri を通じてアプリ外に公開される 質問する

ClipData.Item.getUri を通じてアプリ外に公開される 質問する

Android ファイル システムに新しい機能が追加された後に問題を修正しようとしていますが、次のエラーが発生します。

android.os.FileUriExposedException: file:///storage/emulated/0/MyApp/Camera_20180105_172234.jpg exposed beyond app through ClipData.Item.getUri()

だから誰かがこれを直すのを手伝ってくれるといいな :)

ありがとう

private Uri getTempUri() {
    // Create an image file name
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
    String dt = sdf.format(new Date());
    imageFile = null;
    imageFile = new File(Environment.getExternalStorageDirectory()
            + "/MyApp/", "Camera_" + dt + ".jpg");
    AppLog.Log(
            TAG,
            "New Camera Image Path:- "
                    + Environment.getExternalStorageDirectory()
                    + "/MyApp/" + "Camera_" + dt + ".jpg");
    File file = new File(Environment.getExternalStorageDirectory() + "/MyApp");
    if (!file.exists()) {
        file.mkdir();
    }
    imagePath = Environment.getExternalStorageDirectory() + "/MyApp/"
            + "Camera_" + dt + ".jpg";
    imageUri = Uri.fromFile(imageFile);
    return imageUri;
}

ベストアンサー1

SDK 24 以降では、アプリ ストレージ外のファイルの URI を取得する必要がある場合、このエラーが発生します。
@eranda.del ソリューションでは、ポリシーを変更してこれを許可すると正常に動作します。

ただし、アプリの API ポリシーを変更せずに Google ガイドラインに従う場合は、FileProvider を使用する必要があります。

まず、ファイルの URI を取得するには、FileProvider.getUriForFile() メソッドを使用する必要があります。

Uri imageUri = FileProvider.getUriForFile(
            MainActivity.this,
            "com.example.homefolder.example.provider", //(use your app signature + ".provider" )
            imageFile);

次に、Android マニフェストでプロバイダーを構成する必要があります。

<application>
  ...
     <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.example.homefolder.example.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <!-- ressource file to create -->
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths">  
        </meta-data>
    </provider>
</application>

(「authorities」では、getUriForFile() メソッドの 2 番目の引数と同じ値 (アプリ署名 + 「.provider」) を使用します)

最後に、リソース ファイル「file_paths」を作成する必要があります。このファイルは res/xml ディレクトリの下に作成する必要があります (おそらくこのディレクトリも作成する必要があります)。

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="." />
</paths>

おすすめ記事