在Android 10中没有这样的文件或目录(api 29)。

问题描述 投票:-3回答:1

我正在开发一个照片编辑应用,在编辑完我的照片后,我把它保存到我的本地存储中。它工作得很好,直到安卓9,但不是在安卓10。在Android 10中,它显示 "没有找到这样的文件或目录 "的异常。经过研究,我发现getExternalFilesDir()在android Q+中被废弃了。但我找不到任何合适的方法在Android 10中做。所以,如果有谁能提供一个教程,那将是非常有帮助的。

我已经添加并授予uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" > 以防它是问题,但它没有解决任何问题。

这是我的尝试(使用了ParcelFileDescriptor)。

private void fileAccessForAndroidQ(Uri fileUri){
    try {
        ParcelFileDescriptor parcelFileDescriptor = this.getContentResolver().openFileDescriptor(fileUri, "r", null);
        InputStream inputStream = new FileInputStream(parcelFileDescriptor.getFileDescriptor());
        Cursor returnCursor =
                getContentResolver().query(fileUri, null, null, null, null);
        int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
        returnCursor.moveToFirst();
        fileName = returnCursor.getString(nameIndex);

        file = new File(this.getFilesDir(), fileName);

        OutputStream outputStream = new FileOutputStream(file);
        IOUtils.copyStream(inputStream, outputStream);

    }catch (Exception e){
        Toast.makeText(this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
    }
}

任何形式的帮助都将是感激的。

android file fileoutputstream android-external-storage android-10.0
1个回答
4
投票

如果你的目标是Android 10 (API level 29)或更高版本,请设置下面的值。requestLegacyExternalStoragetrue 在你的应用程序的清单文件中。

文件中

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.appname"
    android:installLocation="auto">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:requestLegacyExternalStorage="true"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme.NoActionBar">

        <activity android:name=".activities.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>


    </application>

</manifest>

1
投票

这是我能找到的最好的。https:/developer.android.comtrainingdata-storageapp-specific#external。

基本上,你现在使用应用程序特定的目录来存放你的文件。比如说

@Nullable
File getAppSpecificAlbumStorageDir(Context context, String albumName) {
    // Get the pictures directory that's inside the app-specific directory on
    // external storage.
    File file = new File(context.getExternalFilesDir(
            Environment.DIRECTORY_PICTURES), albumName);
    if (file == null || !file.mkdirs()) {
        Log.e(LOG_TAG, "Directory not created");
    }
    return file;
}
© www.soinside.com 2019 - 2024. All rights reserved.