修改关闭链接,优化连接蓝牙

master
章文轩 2 years ago
parent 1d11eb7b2c
commit 3d16fd8ee1

@ -164,16 +164,17 @@ public class Bluetooth {
//搜索设备 //搜索设备
public void SearchingBTDevice() { public void SearchingBTDevice() {
new CheckTypesTask().execute(); new CheckTypesTask().execute();
System.out.println("开始搜索"); System.out.println("开始搜索");
} }
public int btConn(final String address, Context context) throws Exception { public void btConn(final String address, Context context) throws Exception {
// bluetoothPort.connect(address);
//final int[] portOpen = {}; System.out.println("btConn");
final int[] portOpen = new int[1];
btThread = new Thread(new Runnable() { btThread = new Thread(new Runnable() {
@Override @Override
@ -181,9 +182,11 @@ public class Bluetooth {
// TODO Auto-generated method stub // TODO Auto-generated method stub
try { try {
System.out.println(address); System.out.println(address);
portOpen[0] = PrinterHelper.portOpenBT(context,address); final int result = PrinterHelper.portOpenBT(context,address);
PrinterHelper.logcat("portOpen:"+ portOpen[0]); PrinterHelper.logcat("portOpen result:"+ result);
System.out.println(portOpen[0]); System.out.println(result);
} catch (Exception e) { } catch (Exception e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
@ -193,8 +196,6 @@ public class Bluetooth {
btThread.start(); btThread.start();
//final int result = PrinterHelper.portOpenBT(context,address); //final int result = PrinterHelper.portOpenBT(context,address);
//new connBT().execute(address); //new connBT().execute(address);
return portOpen[0];
} }
//断开连接 //断开连接
@ -202,9 +203,15 @@ public class Bluetooth {
try { try {
// bluetoothPort.disconnect(); // bluetoothPort.disconnect();
PrinterHelper.portClose(); PrinterHelper.portClose();
if ((btThread != null) && (btThread.isAlive())) // if ((btThread != null) && (btThread.isAlive()))
btThread.interrupt(); // btThread.interrupt();
if ((btThread != null) && (btThread.isAlive())) {
Thread dummy = btThread;
btThread = null;
dummy.interrupt();
}else{
return;
}
disconnectflags = true; disconnectflags = true;
context.unregisterReceiver(connectDevice); context.unregisterReceiver(connectDevice);
@ -271,53 +278,45 @@ public class Bluetooth {
class connBT extends AsyncTask<String, Void, Integer> { // class connBT extends AsyncTask<String, Void, Integer> {
//
//
@Override // @Override
protected Integer doInBackground(String... strings) { // protected Integer doInBackground(String... strings) {
Integer retVal = null; // Integer retVal = null;
//
//bluetoothPort.connect(strings[0]); // //bluetoothPort.connect(strings[0]);
//
retVal = Integer.valueOf(0); // retVal = Integer.valueOf(0);
//
return retVal; // return retVal;
} // }
//
@Override // @Override
protected void onPreExecute() { // protected void onPreExecute() {
//
super.onPreExecute(); // super.onPreExecute();
} // }
//
@Override // @Override
protected void onPostExecute(Integer result) { // protected void onPostExecute(Integer result) {
if (result.intValue() == 0) // Connection success. // if (result.intValue() == 0) // Connection success.
{ // {
// RequestHandler rh = new RequestHandler(); //// RequestHandler rh = new RequestHandler();
// btThread = new Thread(rh); //// btThread = new Thread(rh);
// btThread.start(); //// btThread.start();
} else // Connection failed. // } else // Connection failed.
{ // {
//
} // }
super.onPostExecute(result); // super.onPostExecute(result);
} // }
} // }
public void ExcuteDisconnect(Context context) { public void ExcuteDisconnect(Context context) {
new ExcuteDisconnectBT().execute(context); // new ExcuteDisconnectBT().execute(context);
}
private class ExcuteDisconnectBT extends AsyncTask<Context, Void, Void> {
@Override
protected Void doInBackground(Context... contexts) {
try { try {
DisconnectDevice(contexts[0]); DisconnectDevice(context);
while (true) { while (true) {
if (disconnectflags) if (disconnectflags)
@ -329,24 +328,45 @@ public class Bluetooth {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
;
@Override
protected void onPostExecute(Void result) {
disconnectflags = false;
super.onPostExecute(result);
}
;
} }
// private class ExcuteDisconnectBT extends AsyncTask<Context, Void, Void> {
//
//
// @Override
// protected Void doInBackground(Context... contexts) {
// try {
// DisconnectDevice(contexts[0]);
//
// while (true) {
// if (disconnectflags)
// break;
//
// Thread.sleep(100);
// }
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// return null;
// }
//
// @Override
// protected void onPreExecute() {
// super.onPreExecute();
// }
//
// ;
//
//
// @Override
// protected void onPostExecute(Void result) {
// disconnectflags = false;
// super.onPostExecute(result);
// }
//
// ;
// }
} }

@ -4,7 +4,6 @@ import android.content.Context;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import cpcl.PrinterHelper;
import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.EventChannel; import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodCall;
@ -66,14 +65,12 @@ public class HyPrinterPlugin implements FlutterPlugin, MethodCallHandler {
if (call.method.equals("startSearch")) { if (call.method.equals("startSearch")) {
bluetooth.SearchingBTDevice(); bluetooth.SearchingBTDevice();
} else if (call.method.equals("connect")) { } else if (call.method.equals("connect")) {
int code;
String arg = call.argument("address"); String arg = call.argument("address");
System.out.println(arg);
try { try {
code = bluetooth.btConn(arg,context); System.out.println("开始打印");
System.out.println(code); bluetooth.btConn(arg,context);
//PrinterHelper.portOpenBT(context,"04:7F:0E:95:FD:A1"); result.success(true);
result.success(code);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -105,19 +102,11 @@ public class HyPrinterPlugin implements FlutterPlugin, MethodCallHandler {
} }
result.success(sta); result.success(sta);
} else if (call.method.equals("disposeDiscovery")) { } else if (call.method.equals("disposeDiscovery")) {
try {
PrinterHelper.portClose();
} catch (Exception e) {
e.printStackTrace();
}
bluetooth.cancelDiscoveryResult(context); bluetooth.cancelDiscoveryResult(context);
result.success(true); result.success(true);
} else if (call.method.equals("disposeConnect")) { } else if (call.method.equals("disposeConnect")) {
try {
PrinterHelper.portClose();
} catch (Exception e) {
e.printStackTrace();
}
bluetooth.ExcuteDisconnect(context); bluetooth.ExcuteDisconnect(context);
result.success(true); result.success(true);
} }

@ -21,33 +21,14 @@ class MyApp extends StatefulWidget {
class _MyAppState extends State<MyApp> { class _MyAppState extends State<MyApp> {
List<Device> devices = []; List<Device> devices = [];
var cancel;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
initPlatformState(); initPlatformState();
} }
// Future<void> initPlatformState() async {
// if (!mounted) return;
// setState(() {});
// }
Future<void> initPlatformState() async { Future<void> initPlatformState() async {
// var per = await Permission.bluetooth.isGranted;
// if (!per) {
// Permission.bluetooth.request();
// }
// var pers = await Permission.locationWhenInUse.isGranted;
// if (!pers) {
// Permission.locationWhenInUse.request();
// }
// var per1 = await Permission.bluetoothScan.isGranted;
// if (!per1) {
// Permission.bluetoothScan.request();
// }
// var per2 = await Permission.bluetoothConnect.isGranted;
// if (!per2) {
// Permission.bluetoothConnect.request();
// }
DjPrinter().init(); DjPrinter().init();
DjPrinter().addDiscoveryListen(onReceive: (data) { DjPrinter().addDiscoveryListen(onReceive: (data) {
@ -58,25 +39,23 @@ class _MyAppState extends State<MyApp> {
address: js['address'], address: js['address'],
isPaired: js['isPaired'])); isPaired: js['isPaired']));
} }
setState(() {}); setState(() {});
}, onStart: () { }, onStart: () {
print("————————————————————————"); print("————————————————————————");
}, onFinish: () { }, onFinish: () {
print('——————————————————————————————'); print('——————————————————————————————');
DjPrinter().cancelDiscovery(); DjPrinter().cancelDiscovery();
cancel();
}); });
DjPrinter().addConnectListen(onConnect: () { DjPrinter().addConnectListen(onConnect: () {
print("connected"); print("connected");
}, onDisconnect: () { }, onDisconnect: () {
print('disconnected'); print('disconnected');
}); });
print('jieshu');
} }
@override @override
Widget build(BuildContext context) {return MaterialApp( Widget build(BuildContext context) {return MaterialApp(
title: '安速货运', title: '安速货运',
@ -87,10 +66,130 @@ class _MyAppState extends State<MyApp> {
child: BotToastInit().call(context, widget)); child: BotToastInit().call(context, widget));
}, },
navigatorObservers: [BotToastNavigatorObserver()], navigatorObservers: [BotToastNavigatorObserver()],
home: const ScanPage() home: Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: const Text('设备列表',style: TextStyle(color: Colors.white),),
),
body: Center(
child: Column(
children: [
TextButton(
onPressed: () {
devices.clear();
setState(() {});
cancel =
BotToast.showLoading(wrapToastAnimation: (controller, func, child) {
return discoveryLoadingWidget();
});
DjPrinter().startSearch;
},
child: const Text('扫描设备')),
// TextButton(onPressed: () {}, child: const Text('打印')),
const SizedBox(
height: 20,
),
...devices
.map((e) => TextButton(
onPressed: ()async {
BotToast.showLoading(wrapToastAnimation: (controller, func, child) {
return discoveryLoadingWidget();
});
await DjPrinter().connect(e.address).then((value) {
print("main value result");
print(value);
if(value!=null&&value){
BotToast.closeAllLoading();
}
});
// Future.delayed(Duration(seconds: 3), () async {
// if(value==0){
// BotToast.closeAllLoading();
// }
// });
},
child: Column(
children: [
Text(e.name),
Text(e.address),
],
)))
.toList(),
const SizedBox(
height: 20,
),
TextButton(
onPressed: () {
DjPrinter().printNewAScode(
code: 'ASSZ000000002',
barCode: 'ASSZ0000000020001',
channel: '加拿大温哥华海派快线-卡派 / UPS派送',
country: '美国啊啊',
num: '2',
sum:'99',
offset: 0,
hasPlan: true, );
},
child: const Text('nocode打印')),
TextButton(
onPressed: () {
DjPrinter().printNewAScode(
code: 'ASSZ000000002',
barCode: 'ASSZ0000000020001',
channel: '加拿大温哥华海派快线-卡派 / UPS派送',
country: '美国',
num: '2',
sum:'999',
offset: 0,
hasPlan: false, );
},
child: const Text('noplan打印')),
const SizedBox(
height: 20,
),
TextButton(
onPressed: () {
DjPrinter().disposeConnect();
},
child: const Text('取消链接')),
],
),
),
)
); );
} }
Container discoveryLoadingWidget() {
return Container(
padding: const EdgeInsets.all(15),
decoration: const BoxDecoration(
color: Colors.black54,
borderRadius: BorderRadius.all(Radius.circular(8))),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
CircularProgressIndicator(
backgroundColor: Colors.white,
),
Text(
'扫描中……请稍作等待',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
)
],
),
);
}
} }

@ -69,6 +69,7 @@ class _ScanPageState extends State<ScanPage> {
}, onDisconnect: () { }, onDisconnect: () {
print('disconnected'); print('disconnected');
}); });
print('jieshu');
} }
@ -77,8 +78,9 @@ class _ScanPageState extends State<ScanPage> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar( appBar: AppBar(
title: const Text('设备列表'), title: const Text('设备列表',style: TextStyle(color: Colors.white),),
), ),
body: Center( body: Center(
child: Column( child: Column(
@ -101,19 +103,8 @@ class _ScanPageState extends State<ScanPage> {
...devices ...devices
.map((e) => TextButton( .map((e) => TextButton(
onPressed: ()async { onPressed: ()async {
BotToast.showLoading(wrapToastAnimation: (controller, func, child) {
return discoveryLoadingWidget(); await DjPrinter().connect(e.address);
});
int? value = await DjPrinter().connect(e.address);
Future.delayed(Duration(seconds: 3), () async {
if(value==0){
BotToast.closeAllLoading();
}else{
BotToast.closeAllLoading();
}
});
}, },

@ -78,14 +78,10 @@ class DjPrinter {
bool get hasInit => _hasInit; bool get hasInit => _hasInit;
Future<int?> connect(String address) async { Future<bool?> connect(String address) async {
await Future.delayed(const Duration(milliseconds: 2000), () async { final res = await _channel.invokeMethod('connect', {'address': address});
var res = await _channel.invokeMethod('connect', {'address': address});
print('connect');
print(res);
return res; return res;
});
} }
void disposeDiscovery() { void disposeDiscovery() {

Loading…
Cancel
Save