2

Android N には FileProvider が必要になったようです。そのため、FileProvider を実装して、ネットワークからローカルの一時的な場所にファイルを保存しようとしています。次に、この一時ファイルを読み取る必要があります。

FileProvider をセットアップするためにこれを行いました。

マニフェスト.xml:

</application>
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>
</application>

次に、フォルダーに次のprovider_paths.xmlファイルがあります。res/xml

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

最後に、これは一時ファイルを作成するために必要な Java コードです。

try {

    final File imagePath = new File(getContext().getFilesDir(), "Download");
    final File newFile = new File(imagePath, filename + "." + filePrefix);

    final Uri contentUri = FileProvider.getUriForFile(getContext(), getContext().getApplicationContext().getPackageName() + ".provider", newFile);

    final File tempFile = new File(contentUri.getPath());

    tempFile.getParentFile().mkdirs();
    final FileWriter writer = new FileWriter(tempFile);
    writer.flush();
    writer.close();
    return tempFile;
} catch (IOException e) {
    e.printStackTrace();
    return null;
}

行はfinal FileWriter writer = new FileWriter(tempFile);例外をスローしますjava.io.FileNotFoundException: /Download/TempFile.html (No such file or directory)

私が間違っていることについて何か提案はありますか?ありがとうございました!

更新/編集:

ファイルを保存する現在のアプローチでは、ファイルは次の場所に配置されます。 /storage/emulated/0/Download/TempFile.html

これは、次のようにインテントで消費しようとするまでは問題ありません。

final Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), fileType.getMimeType());
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);

これにより、次の例外がスローされます。

android.os.FileUriExposedException:file:///storage/emulated/0/Download/TempFile.html exposed beyond app through Intent.getData()

4

1 に答える 1