最近接了一个新需求:
内容: 通过手机app实现蓝牙连接称重设备,实现app获取设备重量并接入业务
语言以及工具:
1、flutter + java安卓原生
2、某某牌蓝牙称重蓝牙硬件板块(称榜上拆下来的):
前面走过的坑(只对于我接手的项目而已,并不是说以下文档插件不好):
1、flutter_weigh_serial 1.0.0+2
这个插件我试了,但是和我的gradle版本不兼容,就被我舍弃了
2、bluetooth_print 这个热敏蓝牙打印插件我也试了,可以搜索到该蓝牙设备,但是连接不了
最后没办法,还是老老实实写原生方法
1、建立flutter与原生通道
new MethodChannel(Objects.requireNonNull(getFlutterEngine()).getDartExecutor().getBinaryMessenger(), WEIGHTGET)
.setMethodCallHandler((call, result) -> {
if (call.method.equals("getCount")) {
System.out.println("连接状态" + isopen);
if(isopen){
mBLE_Service.disconnect();
isopen = false;
result.success(isopen);
return;
}
isopen = true;
///==========================
Intent data = getIntent();
mdevice = data.getParcelableExtra("Device");
UART_UUID = data.getStringExtra("DeviceUART");
TXO_UUID = data.getStringExtra("DeviceTXO");
RXI_UUID = data.getStringExtra("DeviceRXI");
// sevice = UUID.fromString(UART_UUID);
// txo = UUID.fromString(TXO_UUID);
// rxi = UUID.fromString(RXI_UUID);
sevice = UUID.fromString("0000FFE0-0000-1000-8000-00805F9B34FB");
txo = UUID.fromString("0000FFE1-0000-1000-8000-00805F9B34FB");
rxi = UUID.fromString("0000FFE1-0000-1000-8000-00805F9B34FB");
// 如果 mdevice 为 null 或者需要设置默认地址
if (mdevice == null || mdevice.getAddress() == null || mdevice.getAddress().isEmpty()) {
String defaultAddress = "88:25:83:F4:F7:4A";
mdevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(defaultAddress);
}
mBLE_Service.setUUID(sevice,txo,rxi);
mBLE_Service.disconnect();
mBLE_Service.connect(mdevice, this);
result.success(isopen);
/======================
} else {
result.notImplemented();
}
});
上面的UUID直接写死固定设备,包括设备的蓝牙地址我都是先直接写死
2、监听蓝牙模块的响应数据
SpBLE mBLE_Service;
mBLE_Service = new SpBLE(this,mHandler);
封装好的蓝牙服务类文件
package com.example.yunhan_demo;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
/**
* This class does all the work for setting up and managing Bluetooth
* connections with other devices. It has a thread that listens for
* incoming connections, a thread for connecting with a device, and a
* thread for performing data transmissions when connected.
*/
public class BluetoothChatService {
// Debugging
private static final String TAG = "BluetoothChatService";
private static final boolean D = true;
// Name for the SDP reco