admin管理员组文章数量:1641901
/**
* 蓝牙工具类
*/
public class BlueToothUtils {
private final String TAG = this.getClass().getSimpleName();
private static BlueToothUtils utils = null;
private BluetoothAdapter bluetoothAdapter;
private final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private Executor executor;
//当前链接蓝牙
private static BluetoothSocket mSocket;
private ArrayList<BluetoothDevice> deviceList = new ArrayList<>();//扫描到的远程蓝牙设备
private Handler handler;
public static BluetoothDevice mDevice = null;
private boolean enabled = false;//蓝牙是否可用
private final int SCANTIME = 5*1000;//扫描时间
private final int requestCode = 2002;//
public static BlueToothUtils getInstance(){
if (utils == null){
synchronized (BlueToothUtils.class){
if (utils == null){
utils = new BlueToothUtils();
}
}
}
return utils;
}
/**
* 判断是否打开蓝牙
* 没有就静默打开
*/
public void isOpen(Handler mHandler){
handler = mHandler;
ReceiveUtils.getInstance().setListener(listener);
BluetoothManager bluetoothManager = (BluetoothManager) MyApplication.context.getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter(); // null:表示不支持蓝牙
if (bluetoothAdapter == null){
return;
}
connetGatt();
}
/**
* 链接已配对蓝牙设备
*/
public void connetGatt(){
if (bluetoothAdapter != null){
// true:处于打开状态, false:处于关闭状态
enabled = bluetoothAdapter.isEnabled();
if (!enabled){
MyApplication.activity.startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE),
requestCode);
}else {//获取已配对蓝牙
Set<BluetoothDevice> devicesSet = bluetoothAdapter.getBondedDevices();
deviceList.clear();
for (BluetoothDevice device : devicesSet) {
deviceList.add(device);
if (handler != null){
handler.sendEmptyMessage(BluetoothActivity.SCAN_SUCC);
}
// LogUtils.log(TAG,"已配对蓝牙" + device.getName());
String connetAddress = (String) SPUtils.get(MyApplication.context, SPUtils.BLUETOOTH_ADDRESS, "");
if (device.getAddress().equals(connetAddress)){
if (bluetoothAdapter.isDiscovering()){
scanning(false);
}
LogUtils.log(TAG,"已配对蓝牙" + device.getName());
connet(device);
}
}
}
}
}
/**
* 扫描设备
*/
public void scanning(boolean enable){
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()){
if (handler != null){
handler.sendEmptyMessage(BluetoothActivity.SCAN_OPEN);
}
return;
}
if (bluetoothAdapter != null){
if (enable){
if (handler != null){
handler.postDelayed(new Runnable() {
@Override
public void run() {
bluetoothAdapter.cancelDiscovery();
handler.sendEmptyMessage(BluetoothActivity.SCAN_CLOSE);
LogUtils.log("BlueToothUtils", "停止扫描设备");
}
}, SCANTIME);
}
deviceList.clear();
connetGatt();
// 寻找蓝牙设备,android会将查找到的设备以广播形式发出去
this.bluetoothAdapter.startDiscovery();
LogUtils.log("BlueToothUtils", "开始扫描设备");
}else {
if (handler != null){
handler.removeCallbacksAndMessages(null);
handler.sendEmptyMessage(BluetoothActivity.SCAN_CLOSE);
}
bluetoothAdapter.cancelDiscovery();
LogUtils.log("BlueToothUtils", "停止扫描设备");
}
}
}
/**
* 注册广播
*/
public void initIntentFilter() {
// 设置广播信息过滤
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
// 注册广播接收器,接收并处理搜索结果
MyApplication.context.registerReceiver(receiver, intentFilter);
}
/**
* 销毁广播
*/
public void unregisterReceiver() {
MyApplication.context.unregisterReceiver(receiver);
}
/**
* 蓝牙广播接收器
*/
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// LogUtils.log(TAG,"搜索到蓝牙设备名称:" + device.getName());
// LogUtils.log(TAG,"搜索到蓝牙设备地址:" + device.getAddress());
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
deviceList.add(device);
if (handler != null){
handler.sendEmptyMessage(BluetoothActivity.SCAN_SUCC);
}
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
LogUtils.log(TAG,"搜索蓝牙设备中...");
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
LogUtils.log(TAG,"设备搜索完毕");
if (handler != null){
handler.sendEmptyMessage(BluetoothActivity.SCAN_SUCC);
}
// bluetoothAdapter.cancelDiscovery();
}
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
if (bluetoothAdapter == null) return;
if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_ON) {
LogUtils.log(TAG,"打开蓝牙");
enabled = bluetoothAdapter.isEnabled();
connetGatt();
} else if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF) {
LogUtils.log(TAG,"关闭蓝牙");
}
}
}
};
/**
* 选择链接蓝牙设备
*/
public void connet(BluetoothDevice device){
if (bluetoothAdapter != null && device != null){
close();
LogUtils.log(TAG,"开始连接蓝牙--" + device.getName());
try {
// final BluetoothSocket socket = dev.createRfcommSocketToServiceRecord(SPP_UUID); //加密传输,Android系统强制配对,弹窗显示配对码
final BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(SPP_UUID); //明文传输(不安全),无需配对
executor = Executors.newCachedThreadPool();
// 开启子线程
executor.execute(new Runnable() {
@Override
public void run() {
mSocket = socket;
mDevice = mSocket.getRemoteDevice();
receiveDate(mSocket); //循环读取
}
});
} catch (Throwable e) {
close();
}
}
}
/**
* 发送数据
*
*/
public void sendData(byte[] by) {
if (!isConnected(null)){
// LogUtils.log(TAG, "请先打开蓝牙");
return;
}
if (null != outputStream) {
outputStream.write(by, 0, by.len);
LogUtils.log( "SerialPortThread--发送数据");
} else {
LogUtils.log("SerialPortUtils", "蓝牙通讯失败");
}
}
/**
* 当前设备与指定设备是否连接
*/
public boolean isConnected(BluetoothDevice dev) {
boolean connected = (mSocket != null && mSocket.isConnected());
if (dev == null)
return connected;
return connected && mSocket.getRemoteDevice().equals(dev);
}
/**
* 关闭链接蓝牙设备
*/
public void cancle(){
try {
if (bluetoothAdapter != null){
bluetoothAdapter.cancelDiscovery();
bluetoothAdapter.disable();
bluetoothAdapter = null;
}
if (mSocket != null){
mSocket.close();
}
ReceiveUtils.getInstance().close();
// unregisterReceiver();
utils = null;
}catch (Exception e){
e.printStackTrace();
}
}
public void receiveDate(BluetoothSocket socket){
try {
mSocket = socket;
if (!mSocket.isConnected()){
mSocket.connect();
}
LogUtils.log(TAG, "连接蓝牙成功--" + mSocket.getRemoteDevice().getName());
outputStream = new DataOutputStream(mSocket.getOutputStream());
DataInputStream in = new DataInputStream(mSocket.getInputStream());
int size = 0;
byte[] buffer;
isExit = false;
while (!isExit){
buffer = new byte[DATA_MAX_LEN];
if (in != null) {
size = in.read(buffer);
if (size > 0) {
checkData(buffer, size);//处理数据
}
}
Thread.sleep(10);
}
}catch (Exception e){
LogUtils.log(TAG, "蓝牙连接失败" + e.getMessage());
close();
e.printStackTrace();
}
}
/**
* 关闭Socket连接
*/
public void close() {
try {
Log.e("-----------", "关闭Socket连接:");
isExit = true;
if (mSocket != null){
mSocket.close();
}
} catch (Throwable e) {
e.printStackTrace();
}
}
}
/**
* 蓝牙接收/发送数据
*/
public class ReceiveUtils {
private final String TAG = this.getClass().getSimpleName();
private static ReceiveUtils utils = null;
private BluetoothSocket mSocket;
private DataOutputStream outputStream;
//是否退出
private boolean isExit = false;
private BlueToothUtils.Listener listener;
/**** 最大长度*/
private static int DATA_MAX_LEN = 10;
/**** 校验和长度*/
private static int checkSumLen = 8;
/***** 初始化*/
private static byte[] b = new byte[DATA_MAX_LEN];
/***** 初始化字节长度*/
private static int unDisposeLen = 0;
/**** 报头:一个字节,暂定0x35*/
private static byte head = (byte) 0xA5;
/**** 报尾:一个字节,暂定0xAA*/
private static byte end = (byte) 0x45;
public static ReceiveUtils getInstance(){
if (utils == null){
synchronized (ReceiveUtils.class){
if (utils == null){
utils = new ReceiveUtils();
}
}
}
return utils;
}
public void setListener(BlueToothUtils.Listener listener){
this.listener = listener;
}
public void receiveDate(BluetoothSocket socket){
try {
mSocket = socket;
if (!mSocket.isConnected()){
mSocket.connect();
}
LogUtils.log(TAG, "连接蓝牙成功--" + mSocket.getRemoteDevice().getName());
if (listener != null){
listener.socketNotify(BlueToothUtils.Listener.CONNECTED, mSocket.getRemoteDevice());
SPUtils.set(MyApplication.context, SPUtils.BLUETOOTH_ADDRESS, mSocket.getRemoteDevice().getAddress());
}
outputStream = new DataOutputStream(mSocket.getOutputStream());
DataInputStream in = new DataInputStream(mSocket.getInputStream());
int size = 0;
byte[] buffer;
isExit = false;
while (!isExit){
buffer = new byte[DATA_MAX_LEN];
if (in != null) {
size = in.read(buffer);
if (size > 0) {
//接收数据
}
}
Thread.sleep(10);
}
}catch (Exception e){
LogUtils.log(TAG, "蓝牙连接失败" + e.getMessage());
close();
e.printStackTrace();
}
}
/***
* 串口写入数据
*/
public void send(byte by) {
try {
if (null != outputStream) {
outputStream.write(by, 0, DATA_MAX_LEN);
// LogWSUtils.logData(by, DATA_MAX_LEN, TAG + "--发送数据");
// LogUtils.log(TAG, "发送数据--" + Arrays.toString(by));
} else {
LogUtils.log(TAG, "蓝牙通讯失败");
}
} catch (IOException e) {
close();
e.printStackTrace();
}
}
/**
* 关闭Socket连接
*/
public void close() {
try {
Log.e("-----------", "关闭Socket连接:");
isExit = true;
if (mSocket != null){
mSocket.close();
mSocket = null;
}
if (listener != null){
listener.socketNotify(BlueToothUtils.Listener.DISCONNECTED, null);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
版权声明:本文标题:Android蓝牙扫描连接收发数据 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dongtai/1729330957a1196390.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论