Scoped storage in Android 11 - React native ??????

Scoped storage in Android 11 - React native ??????

From November 2021, the google play console forced the developers to deploy the Android app, targeting API 30(Android 11). The Android 11 consists of some privacy features, which could update some existing features, which we used earlier in Android 10 and below, like Scoped Storage enforcement, One-time permission, Background location access, etc.

No alt text provided for this image

In React native world, most of the developers are request for updating some packages such as RN-fetch-blob, react-native camera roll, etc. (which requires storage permission for writing data to the file manager)

Today, we are going to learn about how to write files to android 11 external storage(Using react-native)

Let's get started,

Android Native Module:

The native module system exposes instances of Java classes to Javascript as JS objects, thereby allowing you to execute arbitrary native code from within JS. Here, we are going to create a simple Android native module for accessing storage permission in Android 11.

Setup:

Once the react-native project setup was completed, open up the Android project within your React Native application in Android studio.

No alt text provided for this image

Check the target SDK version is 30 in android/build.gradle file,

No alt text provided for this image

Add permissions in the Android manifest file (android/app/src/main/AndroidManifest.xml) for accessing the file system on your device.

No alt text provided for this image

Here, the WRITE_EXTERNAL_STORAGE permission won't work in Android 11, which targets SDK version 30. So, add MANAGE_EXTERNAL_STORAGE permission in the Manifest file. And the READ_EXTERNAL_STORAGE permission will remain the same, it will work for both Android 10 and Android 11.

Create a Custom Native module file:

The first step is to create the PermissionFileModule.java java file inside android/app/src/main/java/com/your-app-name/ folder. This Java file will contain your native module Java class.

No alt text provided for this image

Then, extends ReactContextBaseJavaModule and implements their methods. Then give the module name in the getName() method(The native module can then be accessed in JavaScript using its name)

No alt text provided for this image

Then, create two methods checkPermission() and requestPermission(),

No alt text provided for this image
No alt text provided for this image

Next, you will need to create a native module method, all native module methods must be annotated with @ReactMethod. And check the permission for accessing file manager.

No alt text provided for this image

Next, handling the permission callback in the onActivityResult() method. By this method, we can start another activity from the current activity to get the result for it.

No alt text provided for this image

Register the Module:

Once a native module is written, it needs to be registered with React Native. In order to do so, you need to add your native module to a?ReactPackage?and register the?ReactPackage?with React Native.

To add your Native Module to?ReactPackage, first create a new Java Class named PermissionFilePackage.java?that implements?ReactPackage?inside the?android/app/src/main/java/com/your-app-name/?folder:

No alt text provided for this image

To register the PermissionFileModule package, you must add PermissionFilePackage to the MainApplication.java as a additional package.

No alt text provided for this image

You have now successfully registered your native module for Android!

Accessing PermissionFile in JS component:

In your React native component, call the permission file like this,

import React from 'react
import { NativeModules, PermissionsAndroid, Platform, StyleSheet, Text, TouchableOpacity, View } from 'react-native'


const App = () => {


  const PermissionFile = NativeModules.PermissionFile;


  const accessFiles = () => {
    if (Platform.OS === 'android') {
      checkingManagePermission();
    }
  }


  const checkingManagePermission = () => {
    if (Platform.Version >= 30) {


      PermissionFile.checkGrantPermission(
        err => {
          if (err) {
            console.log('Permission Error', err);
          }
        },
        success => {
          if (success) {

            // You can use RN-fetch-blog to download file and storge into download Manager
            console.log('Access granted!');

          }
        }
      );


    } else {

      // For API 29 and below (Android 10 and below)
      checkingWritePermission();
    }
  }


  const checkingWritePermission = async () => {
    try {
      const granted = await PermissionsAndroid.requestMultiple(
        [PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
        PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE]
      );

      if (granted['android.permission.WRITE_EXTERNAL_STORAGE'] === 'granted' &&
        granted['android.permission.READ_EXTERNAL_STORAGE'] === granted) {

        // You can use RN-fetch-blog to download file and storge into download Manager
        console.log('Access granted!');

      } else {
        console.log('Access to external storage failed.');
      }
    } catch (error) {
        console.log('Access to external storage failed.');
    }
  }


  return (
    <View>
      <TouchableOpacity onPress={accessFiles}>
        <Text>Access File system!</Text>
      </TouchableOpacity>
    </View>
  )
}


export default App;        

I hope, this above article will helps a lot of developers to implement scoped storage permission in their project. This is one way of implementing scoped storage permission in react native ?? Please comment it out, if you have any other way of accessing external storage in Android 11 by using React native ??

If you like the content, please share this article with your friends.

Thanks for reading! Be safe at home!

Happy coding.




Muhammad Tahir

React Native App Developer | NodeJS | ReactJS | Experienced App Developer | Proficient in Website Development | Passionate about Quality Apps and Websites Creation

1 å¹´

Nice one but where is access granted path after user give access to specific folder in scoped storage in your code?

赞
回复
Muhammad Nouman Sajid

Web And Mobile App Developer | Next.js, TypeScript, MongoDB, React, React Native

1 å¹´

code repo?

赞
回复

please give a link to the repository with this code.

赞
回复

要查看或添加评论,请登录

Prasath Ravichandran的更多文章

  • display: flow-root, A nice little alternative for clearfix in CSS.

    display: flow-root, A nice little alternative for clearfix in CSS.

    There are numerous display properties in CSS, but have you heard of flow-root??? Here are the details, In CSS…

  • React native Reanimated - Quick Look??????

    React native Reanimated - Quick Look??????

    React Native, a popular JavaScript-based UI software framework that allows you to build natively rendering mobile apps…

    2 条评论
  • JS [De,structur,ing] assignment ????

    JS [De,structur,ing] assignment ????

    The destructuring assignment is a javascript expression that takes values from arrays or properties from objects and…

  • Async Await try-catch hell ??????

    Async Await try-catch hell ??????

    There are many new features in JavaScript, which were helpful for the developer in day-to-day programming. One of them…

  • What is SvelteJS? How fast is SvelteJS???????

    What is SvelteJS? How fast is SvelteJS???????

    Svelte is a Javascript tool for creating UI components just like React, Angular, and Vue. But Svelte is different from…

  • CSS is too hard(myth) ???

    CSS is too hard(myth) ???

    CSS stands for Cascading style sheet, and it was awesome, ever since it came out in the year 1996 when Netscape was the…

  • An VS Code extension that would replace Postman!!!

    An VS Code extension that would replace Postman!!!

    I have been working in a Postman for testing HTTP requests(REST APIs), but I just found one VS Code extension that…

社区洞察

其他会员也浏览了