Browse Source

feat: check connection status

Raihan Rizal 5 months ago
parent
commit
b1563220f6

+ 15 - 129
android/src/main/java/id/kalanusa/flutter_zsdk/FlutterZsdkPlugin.java

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.bluetoothconnectionhandler.BluetoothConnectionHandler;
22
+import id.kalanusa.flutter_zsdk.bluetoothconnectionhandler.BluetoothConnectionHolder;
22
 import id.kalanusa.flutter_zsdk.bluetoothdiscoveryhandler.BluetoothDiscoveryHandler;
23
 import id.kalanusa.flutter_zsdk.bluetoothdiscoveryhandler.BluetoothDiscoveryHandler;
23
 import id.kalanusa.flutter_zsdk.bluetoothdiscoveryhandler.BluetoothPrinter;
24
 import id.kalanusa.flutter_zsdk.bluetoothdiscoveryhandler.BluetoothPrinter;
24
 import io.flutter.Log;
25
 import io.flutter.Log;
35
 import io.flutter.plugin.common.PluginRegistry;
36
 import io.flutter.plugin.common.PluginRegistry;
36
 
37
 
37
 /** FlutterZsdkPlugin */
38
 /** FlutterZsdkPlugin */
38
-public class FlutterZsdkPlugin implements FlutterPlugin, MethodCallHandler, ActivityAware, PluginRegistry.RequestPermissionsResultListener {
39
+public class FlutterZsdkPlugin implements FlutterPlugin, MethodCallHandler, ActivityAware {
39
   /// The MethodChannel that will the communication between Flutter and native Android
40
   /// The MethodChannel that will the communication between Flutter and native Android
40
   ///
41
   ///
41
   /// This local reference serves to register the plugin with the Flutter Engine and unregister it
42
   /// This local reference serves to register the plugin with the Flutter Engine and unregister it
50
   private DartExecutor dartExecutor;
51
   private DartExecutor dartExecutor;
51
   private BinaryMessenger binaryMessenger;
52
   private BinaryMessenger binaryMessenger;
52
 
53
 
54
+  public BluetoothConnectionHolder bluetoothConnectionHolder;
55
+
56
+  public BluetoothConnectionHandler bluetoothConnectionHandler;
57
+
58
+
53
   @Override
59
   @Override
54
   public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
60
   public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
55
     channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "flutter_zsdk");
61
     channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "flutter_zsdk");
63
   @Override
69
   @Override
64
   public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
70
   public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
65
     activity = binding.getActivity();
71
     activity = binding.getActivity();
66
-    binding.addRequestPermissionsResultListener(this);
67
 
72
 
68
     new EventChannel(binaryMessenger, bluetoothDiscoveryEventChannel).setStreamHandler(new BluetoothDiscoveryHandler(context, activity));
73
     new EventChannel(binaryMessenger, bluetoothDiscoveryEventChannel).setStreamHandler(new BluetoothDiscoveryHandler(context, activity));
69
   }
74
   }
89
 
94
 
90
     switch(call.method) {
95
     switch(call.method) {
91
       case "bluetoothOpenConnection":
96
       case "bluetoothOpenConnection":
92
-        new BluetoothConnectionHandler(call.argument("macAddress")).handle(call, result);
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
-//    }
102
-  }
103
-
104
-  @Override
105
-  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
106
-    channel.setMethodCallHandler(null);
107
-  }
108
-
109
-  @Override
110
-  public boolean onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
111
-    if (requestCode == 1001) { // Check if it'sthe request we initiated
112
-      if (grantResults.length > 0) {
113
-        boolean bluetoothScanGranted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
114
-        boolean bluetoothConnectGranted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
115
-        boolean locationGranted = grantResults[2] == PackageManager.PERMISSION_GRANTED;
116
-
117
-        if (bluetoothScanGranted && bluetoothConnectGranted && locationGranted) {
118
-          // All permissions granted, proceed with Bluetooth operations
119
-          // ... your Bluetooth code here ...
120
-          this.startDiscoverBluetoothPrinters();
121
-        } else {
122
-          System.out.println("Permission Denied, please allow permission to discover bluetooth devices");
123
-          // Handle denied permissions
124
-          // You might display a messageto the user or disable Bluetooth features
125
-          // ... your logic for handling denied permissions ...
97
+      case "isConnected":
98
+        if (bluetoothConnectionHandler == null) {
99
+          bluetoothConnectionHandler = new BluetoothConnectionHandler(bluetoothConnectionHolder);
126
         }
100
         }
127
-      }
128
-    }
129
-
130
-    return true;
131
-  }
132
 
101
 
102
+        bluetoothConnectionHandler.handle(call, result);
103
+        break;
133
 
104
 
134
-//  Bluetooth discovery
135
-  public void findBluetoothPrinters() {
136
-    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
137
-      if (context.checkSelfPermission(Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED ||
138
-              context.checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED ||
139
-              context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
140
-
141
-        activity.requestPermissions(new String[]{
142
-                Manifest.permission.BLUETOOTH_SCAN,
143
-                Manifest.permission.BLUETOOTH_CONNECT,
144
-                Manifest.permission.ACCESS_FINE_LOCATION
145
-        }, 1001);
146
-      } else {
147
-        this.startDiscoverBluetoothPrinters();
148
-      }
149
-    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
150
-      if (context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
151
-        activity.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1002);
152
-      } else {
153
-        this.startDiscoverBluetoothPrinters();
154
-      }
155
     }
105
     }
156
   }
106
   }
157
 
107
 
158
-  public void startDiscoverBluetoothPrinters() {
159
-    new EventChannel(dartExecutor, bluetoothDiscoveryEventChannel).setStreamHandler(
160
-            new EventChannel.StreamHandler() {
161
-
162
-              @Override
163
-              public void onListen(Object arguments, EventChannel.EventSink events) {
164
-                Log.w("From native", "Adding Listener");
165
-                attachEvent = events;
166
-                handler = new Handler();
167
-                startDiscoverBluetoothPrintersRunnable.run();
168
-              }
169
-
170
-              @Override
171
-              public void onCancel(Object arguments) {
172
-                Log.w("From native", "Cancelling Listener");
173
-                handler.removeCallbacks(startDiscoverBluetoothPrintersRunnable);
174
-                handler = null;
175
-                attachEvent = null;
176
-                System.out.println("StreamHandler - onCanceled: ");              }
177
-            }
178
-    );
108
+  @Override
109
+  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
110
+    channel.setMethodCallHandler(null);
179
   }
111
   }
180
-
181
-//  public void startDiscoverBluetoothPrintersRunnable() {
182
-//    new Thread(new Runnable() {
183
-//      @Override
184
-//      public void run() {
185
-//
186
-//    });
187
-//  }
188
-//
189
-  private final Runnable startDiscoverBluetoothPrintersRunnable = new Runnable() {
190
-    @Override
191
-    public void run() {
192
-      ArrayList<BluetoothPrinter> tempDiscoveredPrinterList = new ArrayList<BluetoothPrinter>();
193
-      DiscoveryHandler discoveryHandler = new DiscoveryHandler() {
194
-        @Override
195
-        public void foundPrinter(DiscoveredPrinter discoveredPrinter) {
196
-          Map<String, String> discoveredPrinterDataMap = discoveredPrinter.getDiscoveryDataMap();
197
-          System.out.println("Found printer "  + discoveredPrinterDataMap.get("FRIENDLY_NAME"));
198
-
199
-          BluetoothPrinter bluetoothPrinter = new BluetoothPrinter(discoveredPrinterDataMap.get("FRIENDLY_NAME"), discoveredPrinterDataMap.get("MAC_ADDRESS"));
200
-          tempDiscoveredPrinterList.add(bluetoothPrinter);
201
-          attachEvent.success(tempDiscoveredPrinterList);
202
-        }
203
-
204
-        @Override
205
-        public void discoveryFinished() {
206
-          // return value here, this is asynchronous
207
-          Log.w("From Native", "Discovery Success, found "+ tempDiscoveredPrinterList.size() + " Printer(s)");
208
-          attachEvent.endOfStream();
209
-        }
210
-
211
-        @Override
212
-        public void discoveryError(String s) {
213
-          System.out.println("Error when discovering bluetooth device");
214
-          System.out.println("message:" + s);
215
-        }
216
-      };
217
-
218
-      try {
219
-        BluetoothDiscoverer.findPrinters(context, discoveryHandler);
220
-      } catch (ConnectionException e) {
221
-        System.out.println("Error when finding printers");
222
-//            throw new RuntimeException(e);
223
-      }
224
-    }
225
-  };
226
 }
112
 }

+ 29 - 9
android/src/main/java/id/kalanusa/flutter_zsdk/bluetoothconnectionhandler/BluetoothConnectionHandler.java

13
 import io.flutter.plugin.common.MethodChannel;
13
 import io.flutter.plugin.common.MethodChannel;
14
 
14
 
15
 public class BluetoothConnectionHandler {
15
 public class BluetoothConnectionHandler {
16
-    Connection connection;
16
+    BluetoothConnectionHolder bluetoothConnectionHolder;
17
     String macAddress;
17
     String macAddress;
18
 
18
 
19
-    public BluetoothConnectionHandler(String macAddress) {
20
-        this.macAddress = macAddress;
21
-        connection = new BluetoothConnectionInsecure(macAddress);
19
+    public BluetoothConnectionHandler(BluetoothConnectionHolder bluetoothConnectionHolder) {
20
+        this.bluetoothConnectionHolder = bluetoothConnectionHolder;
22
     }
21
     }
23
 
22
 
24
     public void handle(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
23
     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
 
24
 
28
-        connection = new BluetoothConnectionInsecure(macAddress);
25
+        switch (call.method) {
26
+            case "bluetoothOpenConnection":
27
+                if (bluetoothConnectionHolder == null) {
28
+                    bluetoothConnectionHolder = new BluetoothConnectionHolder(new BluetoothConnectionInsecure(call.argument("macAddress")));
29
+                }
30
+
31
+                openConnection(result);
32
+                break;
29
 
33
 
30
-        openConnection(result);
34
+            case "isConnected":
35
+                checkConnection(result);
36
+                break;
37
+        }
31
     }
38
     }
32
 
39
 
33
     public void openConnection(@NonNull MethodChannel.Result result) {
40
     public void openConnection(@NonNull MethodChannel.Result result) {
36
             public void run() {
43
             public void run() {
37
                 try {
44
                 try {
38
                     Looper.prepare();
45
                     Looper.prepare();
39
-                    connection.open();
46
+                    bluetoothConnectionHolder.connection.open();
40
                     Looper.myLooper().quit();
47
                     Looper.myLooper().quit();
41
                     result.success(null);
48
                     result.success(null);
42
                     Log.w("From Native (Android)", "open connection finished");
49
                     Log.w("From Native (Android)", "open connection finished");
48
         }).start();
55
         }).start();
49
     }
56
     }
50
 
57
 
58
+    public void checkConnection(@NonNull MethodChannel.Result result) {
59
+        new Thread(new Runnable() {
60
+            @Override
61
+            public void run() {
62
+                boolean isConnected = bluetoothConnectionHolder.connection.isConnected();
63
+
64
+                result.success(isConnected);
65
+
66
+                Log.w("From Native (Android)", "isConnected: " + isConnected);
67
+            }
68
+        }).start();
69
+    }
70
+
51
 
71
 
52
 }
72
 }

+ 17 - 0
android/src/main/java/id/kalanusa/flutter_zsdk/bluetoothconnectionhandler/BluetoothConnectionHolder.java

1
+package id.kalanusa.flutter_zsdk.bluetoothconnectionhandler;
2
+
3
+import androidx.annotation.NonNull;
4
+
5
+import com.zebra.sdk.comm.Connection;
6
+
7
+public class BluetoothConnectionHolder {
8
+    public Connection connection;
9
+
10
+    public BluetoothConnectionHolder(@NonNull Connection connection) {
11
+        this.connection = connection;
12
+    }
13
+
14
+    public void updateConnection(@NonNull Connection connection) {
15
+        this.connection = connection;
16
+    }
17
+}

+ 10 - 0
example/lib/main.dart

147
               onPressed: _selectedBluetoothPrinterMacAddress == null || _connectedPrinter != null ? null : openConnection,
147
               onPressed: _selectedBluetoothPrinterMacAddress == null || _connectedPrinter != null ? null : openConnection,
148
             ),
148
             ),
149
             SizedBox(height: 20),
149
             SizedBox(height: 20),
150
+
151
+            ElevatedButton(
152
+              child: Text('Check connection status'),
153
+              onPressed: () async {
154
+                bool isConnected =await _flutterZsdkPlugin.isConnected();
155
+              
156
+                print('isConnected from dart: $isConnected');
157
+              },
158
+            ),
159
+            SizedBox(height: 20),
150
             
160
             
151
             ElevatedButton(
161
             ElevatedButton(
152
               child: Text(_isDiscovering ? 'Discovering bluetooth printers...' : 'Discover nearby bluetooth printers'),
162
               child: Text(_isDiscovering ? 'Discovering bluetooth printers...' : 'Discover nearby bluetooth printers'),

+ 5 - 0
lib/flutter_zsdk.dart

15
   Future<void> openConnection(String macAddress) {
15
   Future<void> openConnection(String macAddress) {
16
     return FlutterZsdkPlatform.instance.openConnection(macAddress);
16
     return FlutterZsdkPlatform.instance.openConnection(macAddress);
17
   }
17
   }
18
+
19
+  /// this api must not be called before FlutterZsdkPlugin.openConnection()
20
+  Future<bool> isConnected() {
21
+    return FlutterZsdkPlatform.instance.isConnected();
22
+  }
18
 }
23
 }

+ 7 - 0
lib/src/flutter_zsdk_method_channel.dart

97
       throw FlutterZsdkException("Failed to open connection to printer: $e");
97
       throw FlutterZsdkException("Failed to open connection to printer: $e");
98
     }
98
     }
99
   }
99
   }
100
+
101
+  @override
102
+  Future<bool> isConnected() async {
103
+    bool isConnected = await methodChannel.invokeMethod('isConnected');
104
+
105
+    return isConnected;
106
+  }
100
 }
107
 }

+ 4 - 0
lib/src/flutter_zsdk_platform_interface.dart

35
   Future<void> openConnection(String macAddress) {
35
   Future<void> openConnection(String macAddress) {
36
     throw UnimplementedError('openConnection() has not been implemented.');
36
     throw UnimplementedError('openConnection() has not been implemented.');
37
   }
37
   }
38
+
39
+  Future<bool> isConnected() {
40
+    throw UnimplementedError('isConnected() has not been implemented.');
41
+  }
38
 }
42
 }