應各大應用市場上架要求,增加權限索取行為用戶交互彈窗
詳細: https://developer.huawei.com/consumer/cn/doc/app/FAQ-faq-05#h1-1698326401789-0
- flutter端使用permission_handler申請權限
- 注冊一個MethodChannel,增加一個函數,提供安卓webview相機/麥克風等權限被觸發時回調用到flutter端
static const platform = MethodChannel('webview_permission');
platform.setMethodCallHandler((MethodCall call) async {// 處理回調switch (call.method) { case 'requestCameraPermission': ...略// 回調showPermissionDialog}
}
- 增加一個通用權限交互彈窗
/// 通用權限彈窗/// @permission/// @title/// @descvoid showPermissionDialog(Permission permission) {showDialog(context: context,builder: (BuildContext context) {return AlertDialog(shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0),),title: Text(title),content: Text(desc),actions: <Widget>[TextButton(child: Text('去授權'),onPressed: () {Navigator.of(context).pop();// 處理權限授予邏輯permission.request().then((status) {print(status.isGranted);});},),TextButton(child: Text('不'),onPressed: () {// 處理權限拒絕邏輯Navigator.of(context).pop();},),],);},);}
- 安卓端同樣注冊MethodChannel
import android.content.pm.PackageManager;
import androidx.core.content.ContextCompat;
...略
//
methodChannel4Premission = new MethodChannel(messenger, "webview_permission");
methodChannel4Premission.setMethodCallHandler(this);
- webview發起申請權限索取時,判斷是否已授權,未授權時通過methodChannel調用flutter彈窗向用戶說明權限用途
判斷是否已授權麥克風權限
if (ContextCompat.checkSelfPermission(WebViewFlutterPlugin.activity, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {methodChannel4Premission.invokeMethod("requestMicroPhonePermission", null);}
判斷是否已授權相機權限
if (ContextCompat.checkSelfPermission(WebViewFlutterPlugin.activity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {methodChannel4Premission.invokeMethod("requestCameraPermission", null);}
- flutter端批量索取權限
// 列出需要請求的權限Map<Permission, PermissionStatus> statuses = {Permission.camera: await Permission.camera.status,Permission.location: await Permission.location.status,Permission.microphone: await Permission.microphone.status,};bool allPermissionsGranted = true;for (final entry in statuses.entries) {if (entry.value != PermissionStatus.granted) {allPermissionsGranted = false;break;}}if (allPermissionsGranted) {// 所有權限都已授權,調用成功的回調函數onSuccess();} else {// 批量索取權限await [Permission.camera,Permission.location,Permission.microphone,].request();}