英文:
exception in UsbManager.openDevice Flutter
问题
这个错误信息表明你的应用程序缺少USB设备访问权限,这导致无法打开USB设备。要解决这个问题,你需要确保你的应用程序已经请求了USB设备的权限。你可以在你的Flutter应用程序的Android清单文件(通常是AndroidManifest.xml
)中添加USB设备的权限请求。
在清单文件中,你可以添加以下代码:
<uses-feature android:name="android.hardware.usb.host" />
<uses-permission android:name="android.permission.USB_PERMISSION" />
这将请求USB主机特性和USB许可权限,以便你的应用程序能够与USB设备进行通信。确保你的清单文件中包含了这些权限后,重新构建你的Flutter应用程序,然后再次运行它。
这应该解决你遇到的USB设备权限问题。如果你在运行应用程序时仍然遇到问题,还需要确保你的设备在物理上支持USB主机模式,并且USB设备已正确连接到设备上。
英文:
I'm trying to connect my flutter app with USB serial devices to interact with it.
for that, I'm using the usb_serial plugin and using the official example below.
Also, I'm running my app on a Desktop monitor using TvBox H96Max.
`import 'dart:async';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:usb_serial/transaction.dart';
import 'package:usb_serial/usb_serial.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
UsbPort? _port;
String _status = "Idle";
List<Widget> _ports = [];
List<Widget> _serialData = [];
StreamSubscription<String>? _subscription;
Transaction<String>? _transaction;
UsbDevice? _device;
TextEditingController _textController = TextEditingController();
Future<bool> _connectTo(device) async {
_serialData.clear();
if (_subscription != null) {
_subscription!.cancel();
_subscription = null;
}
if (_transaction != null) {
_transaction!.dispose();
_transaction = null;
}
if (_port != null) {
_port!.close();
_port = null;
}
if (device == null) {
_device = null;
setState(() {
_status = "Disconnected";
});
return true;
}
_port = await device.create();
if (await (_port!.open()) != true) {
setState(() {
_status = "Failed to open port";
});
return false;
}
_device = device;
await _port!.setDTR(true);
await _port!.setRTS(true);
await _port!.setPortParameters(115200, UsbPort.DATABITS_8, UsbPort.STOPBITS_1, UsbPort.PARITY_NONE);
_transaction = Transaction.stringTerminated(_port!.inputStream as Stream<Uint8List>, Uint8List.fromList([13, 10]));
_subscription = _transaction!.stream.listen((String line) {
setState(() {
_serialData.add(Text(line));
if (_serialData.length > 20) {
_serialData.removeAt(0);
}
});
});
setState(() {
_status = "Connected";
});
return true;
}
void _getPorts() async {
_ports = [];
List<UsbDevice> devices = await UsbSerial.listDevices();
if (!devices.contains(_device)) {
_connectTo(null);
}
print(devices);
devices.forEach((device) {
_ports.add(ListTile(
leading: Icon(Icons.usb),
title: Text(device.productName!),
subtitle: Text(device.manufacturerName!),
trailing: ElevatedButton(
child: Text(_device == device ? "Disconnect" : "Connect"),
onPressed: () {
_connectTo(_device == device ? null : device).then((res) {
_getPorts();
});
},
)));
});
setState(() {
print(_ports);
});
}
@override
void initState() {
super.initState();
UsbSerial.usbEventStream!.listen((UsbEvent event) {
_getPorts();
});
_getPorts();
}
@override
void dispose() {
super.dispose();
_connectTo(null);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('USB Serial Plugin example app'),
),
body: Center(
child: Column(children: <Widget>[
Text(_ports.length > 0 ? "Available Serial Ports" : "No serial devices available", style: Theme.of(context).textTheme.headline6),
..._ports,
Text('Status: $_status\n'),
Text('info: ${_port.toString()}\n'),
ListTile(
title: TextField(
controller: _textController,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Text To Send',
),
),
trailing: ElevatedButton(
child: Text("Send"),
onPressed: _port == null
? null
: () async {
if (_port == null) {
return;
}
String data = _textController.text + "\r\n";
await _port!.write(Uint8List.fromList(data.codeUnits));
_textController.text = "";
},
),
),
Text("Result Data", style: Theme.of(context).textTheme.headline6),
..._serialData,
])),
));
}
}`
It gives me this error message:
`exception in UsbManager.openDevice
E/UsbManager(19118): java.lang.SecurityException: User has not given 10087/com.example.untitled4 permission to access device /dev/bus/usb/001/002
E/UsbManager(19118): at android.os.Parcel.createExceptionOrNull(Parcel.java:2426)
E/UsbManager(19118): at android.os.Parcel.createException(Parcel.java:2410)
E/UsbManager(19118): at android.os.Parcel.readException(Parcel.java:2393)
E/UsbManager(19118): at android.os.Parcel.readException(Parcel.java:2335)
E/UsbManager(19118): at android.hardware.usb.IUsbManager$Stub$Proxy.openDevice(IUsbManager.java:1022)
E/UsbManager(19118): at android.hardware.usb.UsbManager.openDevice(UsbManager.java:719)
E/UsbManager(19118): at dev.bessems.usbserial.UsbSerialPlugin.openDevice(UsbSerialPlugin.java:145)
E/UsbManager(19118): at dev.bessems.usbserial.UsbSerialPlugin.createTyped(UsbSerialPlugin.java:186)
E/UsbManager(19118): at dev.bessems.usbserial.UsbSerialPlugin.onMethodCall(UsbSerialPlugin.java:288)
E/UsbManager(19118): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:258)
E/UsbManager(19118): at io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:295)
E/UsbManager(19118): at io.flutter.embedding.engine.dart.DartMessenger.lambda$dispatchMessageToQueue$0$io-flutter-embedding-engine-dart-DartMessenger(DartMessenger.java:322)
E/UsbManager(19118): at io.flutter.embedding.engine.dart.DartMessenger$$ExternalSyntheticLambda0.run(Unknown Source:12)
E/UsbManager(19118): at android.os.Handler.handleCallback(Handler.java:938)
E/UsbManager(19118): at android.os.Handler.dispatchMessage(Handler.java:99)
E/UsbManager(19118): at android.os.Looper.loopOnce(Looper.java:201)
E/UsbManager(19118): at android.os.Looper.loop(Looper.java:288)
E/UsbManager(19118): at android.app.ActivityThread.main(ActivityThread.java:7870)
E/UsbManager(19118): at java.lang.reflect.Method.invoke(Native Method)
E/UsbManager(19118): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
E/UsbManager(19118): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
D/CompatibilityChangeReporter(19118): Compat change id reported: 160794467; UID 10087; state: ENABLED
E/flutter (19118): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(UsbSerialPortAdapter, Failed to acquire USB device., null, null)
E/flutter (19118): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:653:7)
E/flutter (19118): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:315:18)
E/flutter (19118): <asynchronous suspension>
E/flutter (19118): #2 UsbSerial.createFromDeviceId (package:usb_serial/usb_serial.dart:433:33)
E/flutter (19118): <asynchronous suspension>
E/flutter (19118): #3 UsbDevice.create (package:usb_serial/usb_serial.dart:333:13)
E/flutter (19118): <asynchronous suspension>
E/flutter (19118): #4 _MyAppState.build.<anonymous closure> (package:untitled4/main.dart:175:26)
E/flutter (19118): <asynchronous suspension>`
I was trying to show the USB serial devices and interact with it (sending data and so on).
答案1
得分: 0
在我的情况下,它是“Enter”按钮,所以我放置了:
Uint8List.fromList([13, 10])
这对我起作用了。
英文:
It turned out that I have to place the last character of my string, which serves as the string terminator, in the second parameter of Transaction.stringTerminated
in my case it was Enter
button. so I put:
Uint8List.fromList([13, 10])
This is what worked for me.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论