浏览代码

feat: bluetoothConnectionInsecure

Raihan Rizal 5 月之前
父节点
当前提交
811c8e580a

+ 13 - 4
android/src/main/java/id/kalanusa/flutter_zsdk/FlutterZsdkPlugin.java

18
 import java.util.Map;
18
 import java.util.Map;
19
 import java.util.Objects;
19
 import java.util.Objects;
20
 
20
 
21
+import id.kalanusa.flutter_zsdk.bluetoothconnectionhandler.BluetoothConnectionHandler;
21
 import id.kalanusa.flutter_zsdk.bluetoothdiscoveryhandler.BluetoothDiscoveryHandler;
22
 import id.kalanusa.flutter_zsdk.bluetoothdiscoveryhandler.BluetoothDiscoveryHandler;
22
 import id.kalanusa.flutter_zsdk.bluetoothdiscoveryhandler.BluetoothPrinter;
23
 import id.kalanusa.flutter_zsdk.bluetoothdiscoveryhandler.BluetoothPrinter;
23
 import io.flutter.Log;
24
 import io.flutter.Log;
84
 
85
 
85
   @Override
86
   @Override
86
   public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
87
   public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
88
+    Log.w("From Native (Android)", "ini di FLutterZsdkPlugin");
89
+
87
     switch(call.method) {
90
     switch(call.method) {
88
-      case "findBluetoothPrinters":
89
-        findBluetoothPrinters();
90
-      case "getPlatformVersion":
91
-        Log.w("from native", "TEST");
91
+      case "bluetoothOpenConnection":
92
+        new BluetoothConnectionHandler(call.argument("macAddress")).handle(call, result);
92
     }
93
     }
94
+//    switch(call.method) {
95
+//      case "findBluetoothPrinters":
96
+//        findBluetoothPrinters();
97
+//      case "getPlatformVersion":
98
+//        Log.w("from native", "TEST");
99
+//      case "mengege":
100
+//        new BluetoothConnectionHandler(call.argument("macAddress"));
101
+//    }
93
   }
102
   }
94
 
103
 
95
   @Override
104
   @Override

+ 52 - 0
android/src/main/java/id/kalanusa/flutter_zsdk/bluetoothconnectionhandler/BluetoothConnectionHandler.java

1
+package id.kalanusa.flutter_zsdk.bluetoothconnectionhandler;
2
+
3
+import android.os.Looper;
4
+
5
+import androidx.annotation.NonNull;
6
+
7
+import com.zebra.sdk.comm.BluetoothConnectionInsecure;
8
+import com.zebra.sdk.comm.Connection;
9
+import com.zebra.sdk.comm.ConnectionException;
10
+
11
+import io.flutter.Log;
12
+import io.flutter.plugin.common.MethodCall;
13
+import io.flutter.plugin.common.MethodChannel;
14
+
15
+public class BluetoothConnectionHandler {
16
+    Connection connection;
17
+    String macAddress;
18
+
19
+    public BluetoothConnectionHandler(String macAddress) {
20
+        this.macAddress = macAddress;
21
+        connection = new BluetoothConnectionInsecure(macAddress);
22
+    }
23
+
24
+    public void handle(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
25
+        Log.w("From Native (Android)", "ini di BluetoothConnectionHandler");
26
+        Log.w("From Native (Android)", macAddress);
27
+
28
+        connection = new BluetoothConnectionInsecure(macAddress);
29
+
30
+        openConnection(result);
31
+    }
32
+
33
+    public void openConnection(@NonNull MethodChannel.Result result) {
34
+        new Thread(new Runnable() {
35
+            @Override
36
+            public void run() {
37
+                try {
38
+                    Looper.prepare();
39
+                    connection.open();
40
+                    Looper.myLooper().quit();
41
+                    result.success(null);
42
+                    Log.w("From Native (Android)", "open connection finished");
43
+                } catch (ConnectionException e) {
44
+                    Log.w("From Native (Android)", "Connection Exception threw " + e);
45
+                    result.error("OPEN_CONNECTION_ERROR", "Cant Connect to printers", e.getMessage());
46
+                }
47
+            }
48
+        }).start();
49
+    }
50
+
51
+
52
+}

+ 64 - 26
example/lib/main.dart

23
 class _MyAppState extends State<MyApp> {
23
 class _MyAppState extends State<MyApp> {
24
   bool _isDiscovering = false;
24
   bool _isDiscovering = false;
25
   List<BluetoothPrinter> _discoveredBluetoothPrinters = [];
25
   List<BluetoothPrinter> _discoveredBluetoothPrinters = [];
26
-  String _platformVersion = 'Unknown';
26
+  String? _connectedPrinter;
27
   final _flutterZsdkPlugin = FlutterZsdk();
27
   final _flutterZsdkPlugin = FlutterZsdk();
28
+  String? _selectedBluetoothPrinterMacAddress;
28
 
29
 
29
   @override
30
   @override
30
   void initState() {
31
   void initState() {
31
     super.initState();
32
     super.initState();
32
-    initPlatformState();
33
+    // initPlatformState();
33
   }
34
   }
34
 
35
 
35
   // Platform messages are asynchronous, so we initialize in an async method.
36
   // Platform messages are asynchronous, so we initialize in an async method.
36
-  Future<void> initPlatformState() async {
37
-    String platformVersion;
38
-    // Platform messages may fail, so we use a try/catch PlatformException.
39
-    // We also handle the message potentially returning null.
40
-    try {
41
-      platformVersion =
42
-          await _flutterZsdkPlugin.getPlatformVersion() ?? 'Unknown platform version';
43
-    } on PlatformException {
44
-      platformVersion = 'Failed to get platform version.';
45
-    }
46
-
47
-    // If the widget was removed from the tree while the asynchronous platform
48
-    // message was in flight, we want to discard the reply rather than calling
49
-    // setState to update our non-existent appearance.
50
-    if (!mounted) return;
51
-
52
-    setState(() {
53
-      _platformVersion = platformVersion;
54
-    });
55
-  }
37
+  // Future<void> initPlatformState() async {
38
+  //   String platformVersion;
39
+  //   // Platform messages may fail, so we use a try/catch PlatformException.
40
+  //   // We also handle the message potentially returning null.
41
+  //   try {
42
+  //     platformVersion =
43
+  //         await _flutterZsdkPlugin.getPlatformVersion() ?? 'Unknown platform version';
44
+  //   } on PlatformException {
45
+  //     platformVersion = 'Failed to get platform version.';
46
+  //   }
47
+
48
+  //   // If the widget was removed from the tree while the asynchronous platform
49
+  //   // message was in flight, we want to discard the reply rather than calling
50
+  //   // setState to update our non-existent appearance.
51
+  //   if (!mounted) return;
52
+
53
+  //   setState(() {
54
+  //     _platformVersion = platformVersion;
55
+  //   });
56
+  // }
56
 
57
 
57
   StreamSubscription? _bluetoothPrinterSubscription;
58
   StreamSubscription? _bluetoothPrinterSubscription;
58
 
59
 
107
     }
108
     }
108
   }
109
   }
109
 
110
 
111
+  Future<void> openConnection() async {
112
+    print('invoked openConnection from dart');
113
+    try {
114
+      await _flutterZsdkPlugin.openConnection(_selectedBluetoothPrinterMacAddress ?? ''); 
115
+      _connectedPrinter = _selectedBluetoothPrinterMacAddress ?? 'Unknown printer';
116
+      print('Connection opened successfully from dart');
117
+      
118
+    } on FlutterZsdkException catch (e) {
119
+      inspect(e);
120
+      showSnackBar(e.message);
121
+
122
+    } catch (e) {
123
+      inspect(e);
124
+      showSnackBar('Unexpected error while connecting to bluetooth printers');
125
+    }
126
+
127
+    setState(() {});
128
+  }
129
+
110
   @override
130
   @override
111
   Widget build(BuildContext context) {
131
   Widget build(BuildContext context) {
112
     return Scaffold(
132
     return Scaffold(
118
           crossAxisAlignment: CrossAxisAlignment.center,
138
           crossAxisAlignment: CrossAxisAlignment.center,
119
           mainAxisAlignment: MainAxisAlignment.center,
139
           mainAxisAlignment: MainAxisAlignment.center,
120
           children: [
140
           children: [
121
-            Text('Running on: $_platformVersion\n'),
141
+            Text('Connected printer: ${_connectedPrinter ?? "Unknown printer"}\n'),
142
+            Text('Selected printer Mac Address: $_selectedBluetoothPrinterMacAddress\n'),
122
             SizedBox(height: 20),
143
             SizedBox(height: 20),
123
         
144
         
145
+            ElevatedButton(
146
+              child: Text('Connect to $_selectedBluetoothPrinterMacAddress'),
147
+              onPressed: _selectedBluetoothPrinterMacAddress == null || _connectedPrinter != null ? null : openConnection,
148
+            ),
149
+            SizedBox(height: 20),
150
+            
124
             ElevatedButton(
151
             ElevatedButton(
125
               child: Text(_isDiscovering ? 'Discovering bluetooth printers...' : 'Discover nearby bluetooth printers'),
152
               child: Text(_isDiscovering ? 'Discovering bluetooth printers...' : 'Discover nearby bluetooth printers'),
126
               onPressed: _isDiscovering ? null : () async {
153
               onPressed: _isDiscovering ? null : () async {
130
             SizedBox(height: 20),
157
             SizedBox(height: 20),
131
 
158
 
132
             for (var printer in _discoveredBluetoothPrinters) ... [
159
             for (var printer in _discoveredBluetoothPrinters) ... [
133
-              Text(printer.friendlyName),
134
-              Text(printer.macAddress),
135
-              SizedBox(height: 10)
160
+              InkWell(
161
+                onTap: () {
162
+                  _selectedBluetoothPrinterMacAddress = printer.macAddress;
163
+                  setState(() {});
164
+                },
165
+                child: Column(
166
+                  mainAxisSize: MainAxisSize.min,
167
+                  children: [
168
+                    Text(printer.friendlyName),
169
+                    Text(printer.macAddress),
170
+                    SizedBox(height: 10)
171
+                  ],
172
+                ),
173
+              )
136
             ]
174
             ]
137
           ] 
175
           ] 
138
           
176
           

+ 4 - 0
lib/flutter_zsdk.dart

11
   Future<Stream<dynamic>> findBluetoothPrinters() {
11
   Future<Stream<dynamic>> findBluetoothPrinters() {
12
     return FlutterZsdkPlatform.instance.findBluetoothPrinters();
12
     return FlutterZsdkPlatform.instance.findBluetoothPrinters();
13
   }
13
   }
14
+
15
+  Future<void> openConnection(String macAddress) {
16
+    return FlutterZsdkPlatform.instance.openConnection(macAddress);
17
+  }
14
 }
18
 }

+ 16 - 0
lib/src/flutter_zsdk_method_channel.dart

1
 import 'dart:async';
1
 import 'dart:async';
2
+import 'dart:developer';
2
 import 'dart:io';
3
 import 'dart:io';
4
+import 'dart:math';
3
 
5
 
4
 import 'package:flutter/foundation.dart';
6
 import 'package:flutter/foundation.dart';
5
 import 'package:flutter/services.dart';
7
 import 'package:flutter/services.dart';
81
     }
83
     }
82
     
84
     
83
   }
85
   }
86
+
87
+  @override
88
+  Future<void> openConnection(String macAddress) async {
89
+    try {
90
+      await methodChannel.invokeMethod('bluetoothOpenConnection', {'macAddress': macAddress});
91
+
92
+    } on PlatformException catch (e) {
93
+      inspect(e);
94
+      throw FlutterZsdkException("Failed to open connection to printer: ${e.details}");
95
+
96
+    } catch (e) {
97
+      throw FlutterZsdkException("Failed to open connection to printer: $e");
98
+    }
99
+  }
84
 }
100
 }

+ 4 - 0
lib/src/flutter_zsdk_platform_interface.dart

31
   Future<Stream<dynamic>> findBluetoothPrinters() {
31
   Future<Stream<dynamic>> findBluetoothPrinters() {
32
     throw UnimplementedError('findBluetoothPrinters() has not been implemented.');
32
     throw UnimplementedError('findBluetoothPrinters() has not been implemented.');
33
   }
33
   }
34
+
35
+  Future<void> openConnection(String macAddress) {
36
+    throw UnimplementedError('openConnection() has not been implemented.');
37
+  }
34
 }
38
 }