如何在Flutter插件中请求权限?

时间:2017-12-17 18:59:21

标签: android permissions flutter

我正在尝试使用简单的Flutter插件(语音识别包装器),并且不知道如何在Android 23或更新版本上请求相应的权限。在Dart部分我有:

  Future requestPermissions() => 
  _channel.invokeMethod("speech.requestPermissions");

在Android部分:

  public class SpeechRecognitionPlugin implements MethodCallHandler, RecognitionListener,
    PluginRegistry.RequestPermissionResultListener {

插件注册:

  public static void registerWith(Registrar registrar) {
    final MethodChannel channel = new MethodChannel(registrar.messenger(), "speech_recognition");
    SpeechRecognitionPlugin speechRecognitionPlugin = new 
    SpeechRecognitionPlugin(registrar.activity(), channel);
    channel.setMethodCallHandler(speechRecognitionPlugin);
    registrar.addRequestPermissionResultListener(speechRecognitionPlugin);
  }

方法调用:

else if (call.method.equals("speech.requestPermissions")) {
        Log.d(LOG_TAG, "speech.requestPermissions");
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
                Manifest.permission.RECORD_AUDIO)) {
            Toast.makeText(activity.getApplicationContext(), "This application needs the Record Audio permission for recognition to work", Toast.LENGTH_LONG).show();
        } else {
            Log.d(LOG_TAG, "Requesting permissions");
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.RECORD_AUDIO},
                    1);
        }
        result.success(hasRecordAudioPermission());

结果回调:

@Override                                                                                            
public boolean onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) {
    boolean granted = false;
    switch (requestCode) {
        case 1: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                granted = true;
            }
            speechChannel.invokeMethod("speech.onPermission", granted);
            return true;
        }
    }
    return false;
}

从logcat我看到" speech.requestPermissions"调用发生了,但是没有显示标准的Android系统权限请求,只是这在logcat中可能是相关的:

D/ViewRootImpl(21171): #1 mView = android.widget.LinearLayout{64f050b 
V.E...... ......I. 0,0-0,0 #102039d android:id/toast_layout_root}
D/ViewRootImpl(21171): MSG_RESIZED_REPORT: ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=1
D/ViewRootImpl(21171): #3 mView = null

请求Flutter插件权限的正确方法是什么?

编辑:当对话框显示正确时,这不适用于第一次运行,但是当用户最初未授予权限或通过设置撤消权限时,这不适用于后续运行。我意识到这会显着改变这个问题(使它看起来像边缘情况),但Android权限不应该以这种方式工作。

编辑:AndroidManifest.xml中存在权限

3 个答案:

答案 0 :(得分:4)

使用Permission plugin for flutter

请求权限
import 'package:permissions_plugin/permissions_plugin.dart';

Map<Permission, PermissionState> permission = await PermissionsPlugin
    .requestPermissions([
        Permission.ACCESS_FINE_LOCATION,
        Permission.ACCESS_COARSE_LOCATION,
        Permission.READ_PHONE_STATE
    ]);
检查状态权限
import 'package:permissions_plugin/permissions_plugin.dart';

Map<Permission, PermissionState> permission = await PermissionsPlugin
    .checkPermissions([
      Permission.ACCESS_FINE_LOCATION,
      Permission.ACCESS_COARSE_LOCATION,
      Permission.READ_PHONE_STATE
    ]);

答案 1 :(得分:1)

我有这个位置权限。我唯一不同的做法是在你的方法调用中:

ActivityCompat.requestPermissions(activity,
                new String[]{Manifest.permission.RECORD_AUDIO},
                1);

而不是使用&#39; ActivityCompat&#39;我将注册商存储在本地最终变量中,并且我正在执行以下操作:

registrar.activity().requestPermissions(activity,
                new String[]{Manifest.permission.RECORD_AUDIO},
                1);

编辑:还要确保您已在AndroidManifest.xml中包含相关权限

<manifest xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Add this -->
    <uses-permission android:name="android.permission.RECORD_AUDIO" />

    <!-- Flutter stuff --->
</manifest>

答案 2 :(得分:0)

假设您想使用 permission_handler 包请求相机权限。

  1. pubspec.yaml 文件中:

    permission_handler: ^8.0.0+2
    
  2. (Android 版)为 android/app/src/main/AndroidManifest.xml 文件添加权限

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
      <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 
      ...
     </manifest>
    
  3. (对于 iOS),

    (i) 将此添加到您的 info.plist 文件

    <key>NSCameraUsageDescription</key>
    <string>App needs camera permission to work</string>
    

    (ii) 将 'PERMISSION_CAMERA=1' 添加到您的 Podfile

    post_install do |installer|
      installer.pods_project.targets.each do |target|
        flutter_additional_ios_build_settings(target)
    
        target.build_configurations.each do |config|
          config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
            '$(inherited)',
    
            ## Add the following line.
             'PERMISSION_CAMERA=1'
          ]
    
        end
      end
    end
    
  4. 请求权限:

    final status = await Permission.camera.request();
    if (status == PermissionStatus.granted) {
      print('Permission granted');
    } else if (status == PermissionStatus.denied) {
      print('Permission denied. Show a dialog and again ask for the permission');
    } else if (status == PermissionStatus.permanentlyDenied) {
      print('Take the user to the settings page.');
      await openAppSettings();
    }