Use of Dynamic Permissions for Flutter Development

  • 2021-12-19 06:51:46
  • OfStack

Directory basic use 1, configuration authority dynamic authority application 4.3. 05.0. 0

As we all know, Android changed its permissions into dynamic permissions after version 6.0, while iOS used dynamic permissions directly. Therefore, if some dangerous permissions are involved in Flutter application development, it is necessary to apply dynamically, and permission_handler of Flutter can be used to apply for permissions dynamically.

Basic use

1. Configure permissions

First, open the AndroidManifest. xml file under the Android project. The specific path is as follows: Configure in android\ app\ src\ main\ AndroidManifest. xml, and then add the following permissions.


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.kill_attendance">
        <!--  Application Android Authority -->
    <!-- Network access -->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

    <!-- Permissions options for the `contacts` group -->
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.WRITE_CONTACTS" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />

    <!-- Permissions options for the `storage` group -->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <!-- Permissions options for the `camera` group -->
    <uses-permission android:name="android.permission.CAMERA" />

    <!-- Permissions options for the `location` group -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

    <!-- Permissions options for the `microphone` or `speech` group -->
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
         <!-- app Name , Icons  -->
    <application
        android:name="io.flutter.app.FlutterApplication"
        android:label=" Application name "
        android:icon="@mipmap/icon">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- This keeps the window background of the activity showing
                 until Flutter renders its first frame. It can be removed if
                 there is no splash screen (such as the default splash screen
                 defined in @style/LaunchTheme). -->
            <meta-data
                android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
                android:value="true" />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

Dynamic permission application

At present, this plug-in has been upgraded for several versions, and different versions have different processing methods, especially the latest version 5.0. 0 and previous versions, and their usage is quite different.

4.3.0

For example, the following is the usage of version 4.3. 0:

Permission List: Fields in PermissionGroup Permission status list: Fields in PermissionStatus Open the permission setting page: await PermissionHandler (). openAppSettings (); Apply for authority

Examples are as follows:


await Map<PermissionGroup, PermissionStatus> map= PermissionHandler().requestPermissions([  Permission list ])

Then, the status of obtaining the application permission is as follows:


PermissionStatus contactsPermStatus = await PermissionHandler().checkPermissionStatus(PermissionGroup.contacts);

Here is a complete example:


  /// Request permission 
  void _requestPermission() async {
    debugPrint(" Enter the splash screen page ");
    //  Apply for authority 
    // PermissionStatus storageStatus ;
    PermissionStatus cameraStatus;

     await PermissionHandler().requestPermissions(
          [ PermissionGroup.camera]).then((value) {
             debugPrint(" Return :$value");
            // storageStatus=value[PermissionGroup.storage];
            cameraStatus=value[PermissionGroup.camera];
          });
    debugPrint(" Request permission , And get permissions :$cameraStatus");

    // Verification authority 
    if (cameraStatus == PermissionStatus.granted) {
      debugPrint(" Verification authority : The users all agreed ");
      // The users all agreed ( Use &&)
      /// All permissions have been applied for successfully initializing the flash screen 
      _initSplash();
    } else if ( cameraStatus == PermissionStatus.denied) {
      debugPrint(" Verification authority : Have any 1 Group permissions denied by user ");
      // User rejected ( Use ||)
      /// Have any 1 Group permissions denied by user 
      // Splice prompt permission text 
      StringBuffer sb = new StringBuffer();
      sb.write(cameraStatus == PermissionStatus.denied ? " Camera ," : "");
      String tip = Utils.removePostfix(sb.toString(), ",");

      Utils.showCustomDialog(
          context,
          ConfirmDialog(
            " You have denied the necessary permissions to apply :\n[$tip], Do you want to reapply ?",
            canBackDismiss: false,
            confirmCallback: () => _requestPermission(),
            cancelCallback: () => SystemNavigator.pop(),
          ));
    } else if (  cameraStatus == PermissionStatus.neverAskAgain) {
      debugPrint(" Verification authority : Have permission to permanently deny ");
      // Have permission to permanently deny ( Use ||)
      /// Have any 1 Group permission is selected. No Prompt 
      // Splice prompt permission text 
      StringBuffer sb = new StringBuffer();
      sb.write(cameraStatus == PermissionStatus.neverAskAgain ? " Camera ," : "");
      String tip = Utils.removePostfix(sb.toString(), ",");

      Utils.showCustomDialog(
          context,
          ConfirmDialog(
            " You have disabled the necessary permissions to apply :\n[$tip], Please go to the settings to allow ?",
            canBackDismiss: false,
            confirmText: " To set ",
            confirmCallback: () async {
              await PermissionHandler().openAppSettings(); // Open the Settings page 
              SystemNavigator.pop();
            },
            cancelCallback: () => SystemNavigator.pop(),
          ));
    }

  }

5.0.0

Version 5.0. 0 is written in much the same way as before, except that the method and parameter fields are changed, as shown below.

Permission List: Fields in Permission Permission status list: Fields in PermissionStatus Open the permission setting page: openAppSettings (); Apply for authority

await [ Permission list ].request();   // You can use the then, Getting status with permissions 

Get permission status await Permission. camera. status

Judge permission status: await Permission. camera. isDeniedisGranted, etc

The following is a detailed usage example:


  /// Request permission 
  void _requestPermission() async {
    debugPrint(" Enter the splash screen page ");
    //  Apply for authority 
    // PermissionStatus cameraStatus;

    await [Permission.camera].request();
    // .then((value){
      // Set the result after application 
        // cameraStatus=value[Permission.camera];
      // });
    // Or call directly :
    debugPrint(" Request permission , And get permissions ");
    if(await Permission.camera.isDenied){

    }
    
    // Verification authority 
    if (await Permission.camera.isGranted) {
      debugPrint(" Verification authority : The users all agreed ");
      // The users all agreed ( Use &&)
      /// All permissions have been applied for successfully initializing the flash screen 
      _initSplash();
    } else if ( await Permission.camera.isDenied) {
      debugPrint(" Verification authority : Have any 1 Group permissions denied by user ");
      // User rejected ( Use ||)
      /// Have any 1 Group permissions denied by user 
      // Splice prompt permission text 
      StringBuffer sb = new StringBuffer();
      sb.write(await Permission.camera.isDenied? " Camera ," : "");
      String tip = Utils.removePostfix(sb.toString(), ",");

      Utils.showCustomDialog(
          context,
          ConfirmDialog(
            " You have denied the necessary permissions to apply :\n[$tip], Do you want to reapply ?",
            canBackDismiss: false,
            confirmCallback: () => _requestPermission(),
            cancelCallback: () => SystemNavigator.pop(),
          ));
    } else if ( await Permission.camera.isPermanentlyDenied) {
      debugPrint(" Verification authority : Have permission to permanently deny ");
      // Have permission to permanently deny ( Use ||)
      /// Have any 1 Group permission is selected. No Prompt 
      // Splice prompt permission text 
      StringBuffer sb = new StringBuffer();
      sb.write( await Permission.camera.isPermanentlyDenied ? " Camera ," : "");
      String tip = Utils.removePostfix(sb.toString(), ",");

      Utils.showCustomDialog(
          context,
          ConfirmDialog(
            " You have disabled the necessary permissions to apply :\n[$tip], Please go to the settings to allow ?",
            canBackDismiss: false,
            confirmText: " To set ",
            confirmCallback: () async {
              await openAppSettings(); // Open the Settings page 
              SystemNavigator.pop();
            },
            cancelCallback: () => SystemNavigator.pop(),
          ));
    }

  }

Reference: permission_handler


Related articles: