简体   繁体   English

Android 29/Q 上的 MediaScanner scanFile / CameraRoll 的替代方案

[英]Alternative for MediaScanner scanFile / CameraRoll on Android 29/Q

Google Play Store set new requirements regading Android Scoped Storage regarding apps using the manifest flag requestLegacyExternalStorage . Google Play 商店针对使用清单标志requestLegacyExternalStorage的应用程序设置了关于 Android 范围存储的新要求。
My app is using CameraRoll package from React Native community which does not yet support the scoped storage (and require the requestLegacyExternalStorage flag to work) and the timeline is very short ( May 5th 2021 ).我的应用正在使用来自 React Native 社区的 CameraRoll package,该社区尚不支持范围存储(并且需要requestLegacyExternalStorage标志才能工作),而且时间线很短( 2021 年 5 月 5 日)。 Is there any alternative for CameraRoll? CameraRoll 有什么替代品吗? The goal here is to show the image in the user Gallery apps, like Google photos or vendor default Gallery without extra actions on the user side.此处的目标是在用户图库应用程序中显示图像,例如 Google 照片或供应商默认图库,而无需在用户端进行额外操作。

Original Google Play message:原始 Google Play 消息:

 Starting May 5th, you must let us know why your app requires broad storage access APPNAME 14 avr. 2021 19:26 We've detected that your app contains the requestLegacyExternalStorage flag in the manifest file of 1 or more of your app bundles or APKs. Developers with apps on devices running Android 11+ must use Scoped Storage to give users better access control over their device storage. To release your app on Android 11 or newer after May 5th, you must either: Update your app to use more privacy friendly best practices, such as the Storage Access Framework or Media Store API Update your app to declare the All files access (MANAGE_EXTERNAL_STORAGE) permission in the manifest file, and complete the All files access permission declaration in Play Console from May 5th Remove the All files access permission from your app entirely For apps targeting Android 11, the requestLegacyExternalStorage flag will be ignored. You must use the All files access permission to retain broad access. Apps requesting access to the All files access permission without a permitted use will be removed from Google Play, and you won't be able to publish updates.

Digging into ReactNative CameraRoll package, it does much more than simply just scanning the file for the OS to shows up in user Gallery apps.深入研究 ReactNative CameraRoll package,它所做的不仅仅是扫描文件以供操作系统显示在用户图库应用程序中。 The solution here as some repercusion:这里的解决方案有一些影响:

  1. The image need to be in a public directory for it to show up (= read access) in any Gallery apps, so not within the App external storage:图像需要位于公共目录中才能在任何图库应用程序中显示(= 读取访问权限),而不是在应用程序外部存储中:

    • NOT: storage/android/data/com.example/Pictures不是: storage/android/data/com.example/Pictures
    • either in Pictures or DCIM or Download (check Environment.DIRECTORY_DCIM siblings)PicturesDCIMDownload中(检查Environment.DIRECTORY_DCIM兄弟姐妹)
  2. Need a native package for android android 需要原生 package

The code:编码:

React Native part:反应原生部分:

import RNFS from 'react-native-fs'
const { PNModule } = ReactNative.NativeModules

try {
    if (Platform.OS === 'android' && Platform.Version >= 29) {
        // Google ask that the requestLegacyExternalStorage is no longer used when targeting android 11, and use
        // the scoped storage or the new global permission, see https://gitlab.inria.fr/floristic/pn-mobile-test/-/issues/417
        // Solution here, custom module which use the MediaStore API and copy the file to the DCIM folders.
        const segments = path.split('/')
        const fileName = segments[segments.length - 1]

        const fileUriPath = await PNModule.moveToMediaStore(path.replace('file://', ''), fileName)
        if (!fileUriPath) {
            return null
        }
        const scanResult = await RNFS.scanFile(fileUriPath)
        if (fileUriPath.startsWith('file:///')) {
            return fileUriPath
        }
        return `file://${fileUriPath}`
    }
    return await CameraRoll.save(path)
} catch (error) {
    console.error(error)
}

Native package (don't forget to replace the APPNAME by your app folder)本机 package (不要忘记用您的应用文件夹替换APPNAME

    @ReactMethod
    public void moveToMediaStore(String filePath, String fileName, Promise promise) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            promise.resolve(null);
            return;
        }
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");

        values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM + "/APPNAME");
        values.put(MediaStore.MediaColumns.IS_PENDING, 1);

        ContentResolver resolver = getReactApplicationContext().getContentResolver();
        Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

        try {
            OutputStream fos = resolver.openOutputStream(imageUri);
            copy(new File(filePath), fos);
            values.clear();
            values.put(MediaStore.Video.Media.IS_PENDING, 0);
            resolver.update(imageUri, values, null, null);
            promise.resolve(getNameFromContentUri(getReactApplicationContext(), imageUri));
        } catch (Exception e) {
            e.printStackTrace();
            promise.reject(e);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    public static void copy(File src, OutputStream out) throws IOException {
        try (InputStream in = new FileInputStream(src)) {
            FileUtils.copy(in, out);
        }
    }

    // From https://stackoverflow.com/a/64359655/1377145
    public static String getNameFromContentUri(Context context, Uri contentUri){
        ContentResolver contentResolver = context.getContentResolver();
        Cursor cursor = contentResolver.query(contentUri, null, null, null, null);
        cursor.moveToFirst();
        String document_id = cursor.getString(0);
        document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
        cursor.close();

        cursor = contentResolver.query(
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
        cursor.moveToFirst();
        String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
        cursor.close();
        return path;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM