Я работаю над приложением Flutter, в котором использую webview_flutter для отображения веб-страницы внутри WebView. Приложение работает нормально в большинстве случаев использования, но я столкнулся с одной основной проблемой:
Разрешение на медиапоток отклонено: я получаю сообщение об ошибке, связанное с разрешением медиапотока, когда поступает входящий вызов. Приложение запрашивает разрешения для микрофона, камеры, местоположения и телефона, но WebView выдает ошибку «Отказано в разрешении на поток мультимедиа».
Ниже приведен код виджета WebViewScreen и конфигурация MainActivity.kt для Андроид:
package com.example.web_phone
import android.os.Build
import android.webkit.PermissionRequest
import android.webkit.WebChromeClient
import android.webkit.WebView
import androidx.annotation.NonNull
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.GeneratedPluginRegistrant
import io.flutter.plugin.common.MethodChannel
import android.provider.Settings
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity(){
private var CHANNEL = "device/info";
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine){
MethodChannel(flutterEngine.dartExecutor.binaryMessenger,CHANNEL).setMethodCallHandler{
call, result ->
if(call.method == "deviceId"){
var mid = Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID)
result.success(mid)
}else{
result.notImplemented()
}
}
super.configureFlutterEngine(flutterEngine)
// Configure WebView for media permissions
val webView = WebView(this)
webView.webChromeClient = object : WebChromeClient() {
override fun onPermissionRequest(request: PermissionRequest) {
// Grant all requested permissions for the WebView
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
request.grant(request.resources)
}
}
}
}
}
ниже приведен код WebViewScreen
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:web_phone/config/routes/routes_name.dart';
import 'package:web_phone/constant/use_colors.dart';
import 'package:webview_flutter/webview_flutter.dart';
class WebViewScreen extends StatefulWidget {
final String phoneNumber;
const WebViewScreen({super.key, required this.phoneNumber});
@override
State createState() => _WebViewScreenState();
}
class _WebViewScreenState extends State {
bool hasError = false;
late final WebViewController _controller;
bool _hasLoaded = false;
void _reloadWebView() {
_controller.reload();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (!_hasLoaded) {
_hasLoaded = true;
_initializeWebView();
}
}
Future requestPermissions() async {
await [
Permission.microphone,
Permission.camera,
Permission.location,
Permission.phone,
Permission.accessMediaLocation,
Permission.audio,
].request();
}
void _initializeWebView() {
requestPermissions();
_controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..loadRequest(Uri.parse(
"URL"));
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: UseColors.primaryColor,
title: Text(
"Web Phone",
style: TextStyle(color: UseColors.backgroundColor),
),
actions: [
IconButton(
icon: Icon(Icons.refresh, color: UseColors.backgroundColor),
onPressed: _reloadWebView,
),
PopupMenuButton(
icon: Icon(Icons.more_vert, color: UseColors.backgroundColor),
onSelected: (value) {
if (value == 'logout') {
Navigator.pushReplacementNamed(context, RoutesName.authScreen);
}
},
itemBuilder: (BuildContext context) {
return [
PopupMenuItem(
value: 'logout',
child: Row(
children: [
Icon(Icons.exit_to_app, color: UseColors.primaryColor),
SizedBox(width: 8),
Text('Logout'),
],
),
),
];
},
),
],
),
body: WillPopScope(
onWillPop: () async {
return false;
},
child: Stack(
children: [
Visibility(
visible: !hasError,
child: WebViewWidget(controller: _controller),
),
if (hasError)
Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.error_outline, size: 80, color: Colors.red),
SizedBox(height: 16),
Text(
'Unable to load the webpage.',
style: TextStyle(fontSize: 18, color: Colors.black),
),
Text(
'Please check your network or try again later.',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 16, color: Colors.grey),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
setState(() {
hasError = false;
});
_controller.reload();
},
child: Text('Retry'),
),
],
),
),
],
),
),
);
}
}
ниже приведены разрешения, которые я дал в Androidmanifext.xml
Подробнее здесь: https://stackoverflow.com/questions/793 ... er-webview
Как исправить отказ в разрешении медиапотока во Flutter WebView? ⇐ Android
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Как исправить отказ в разрешении при запуске поставщика/bin/phpunit в проекте laravel
Anonymous » » в форуме Php - 0 Ответы
- 17 Просмотры
-
Последнее сообщение Anonymous
-