Android 蓝牙通信
程序员文章站
2024-03-24 23:26:58
...
蓝牙工具类
/**
* @anthor GrainRain
* @funcation 蓝牙工具类 提供回调接口和发送方法
* @date 2019/10/25
*/
public class BluetoothUtil {
private static BluetoothUtil bluetoothUtil;
//这条是蓝牙串口通用的UUID,不要更改
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
//device var
private BluetoothAdapter mBluetoothAdapter = null;
private static BluetoothSocket btSocket = null;
private static OutputStream outStream = null;
private InputStream inStream = null;
private ReceiveThread rThread=null; //数据接收线程
private MyHandler handler;
//连接状态
private static String statusLabel = "";
private OnConnectListener onConnectListener;
//初始化对象
public static BluetoothUtil get() {
if(bluetoothUtil == null) {
bluetoothUtil = new BluetoothUtil();
}
return bluetoothUtil;
}
public BluetoothUtil() {
}
public void initBluetooth() {
//得到一个蓝牙适配器
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null) {
Log.e("Bluetooth", "你的手机不支持蓝牙");
return;
}
}
//创建方法
public void getMsg(String mac, OnConnectListener listener) {
initBluetooth();
handler = new MyHandler();
//判断蓝牙是否打开
if(!mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.enable();
}
//自动配对
//mBluetoothAdapter.startDiscovery();
//创建连接
//mac 要连接的目标蓝牙设备MAC地址
new ConnectTask().execute(mac);
setOnConnectListener(listener);
listener.onConnectSuccess(null);
listener.onConnectFailed(null);
}
//连接蓝牙设备的异步任务
class ConnectTask extends AsyncTask<String,String,String> {
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(params[0]);
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
btSocket.connect();
Log.e("error", "ON RESUME: BT connection established, data transfer link open.");
} catch (IOException e) {
try {
//将异常信息传递给回调接口
if(getOnConnectListener() != null) {
getOnConnectListener().onConnectFailed(e);
}
btSocket.close();
return "Socket 创建失败";
} catch (IOException e2) {
//将异常信息传递给回调接口
if(getOnConnectListener() != null) {
getOnConnectListener().onConnectFailed(e2);
}
Log .e("error","ON RESUME: Unable to close socket during connection failure", e2);
return "Socket 关闭失败";
}
}
//取消搜索
mBluetoothAdapter.cancelDiscovery();
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
//将异常信息传递给回调接口
if(getOnConnectListener() != null) {
getOnConnectListener().onConnectFailed(e);
}
Log.e("error", "ON RESUME: Output stream creation failed.", e);
return "Socket 流创建失败";
}
return "蓝牙连接正常,Socket 创建成功";
}
@Override //这个方法是在主线程中运行的,所以可以更新界面
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
//连接成功则启动监听
rThread = new ReceiveThread();
rThread.start();
statusLabel = result;
Log.e("Bluetooth", "连接状态:" + result);
super.onPostExecute(result);
}
}
//从蓝牙接收信息的线程
class ReceiveThread extends Thread {
String buffer="";
@Override
public void run() {
while(btSocket != null ) {
//定义一个存储空间buff
byte[] buff = new byte[1024];
try {
inStream = btSocket.getInputStream();
System.out.println("waitting for instream");
if(inStream != null) {
inStream.read(buff); //读取数据存储在buff数组中
}
processBuffer(buff,1024);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void processBuffer(byte[] buff,int size) {
int length = 0;
for(int i = 0; i < size; i++) {
if(buff[i] > '\0') {
length++;
} else {
break;
}
}
//newbuff字节数组,用于存放真正接收到的数据
byte[] newbuff = new byte[length];
int[] receiveData = new int[length];
for(int j = 0; j < length; j++) {
newbuff[j] = buff[j];
receiveData[j] = buff[j] & 0xff;
}
Log.w("收到数据: ", Arrays.toString(receiveData));
//回调
if(getOnConnectListener() != null) {
getOnConnectListener().onConnectSuccess(receiveData);
}
Message msg= Message.obtain();
msg.what=1;
handler.sendMessage(msg); //发送消息:系统会自动调用handleMessage( )方法来处理消息
}
}
//发送数据到蓝牙设备的异步任务
static class SendInfoTask extends AsyncTask<String,String,String> {
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
statusLabel = result;
Log.e("Bluetooth", "连接状态:" + result);
}
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
if(btSocket == null) {
return "还没有创建连接";
}
if(arg0[0].length()>0) {
//不是空白串
//String target=arg0[0];
byte[] msgBuffer = arg0[0].getBytes();
try {
if(outStream != null) {
// 将msgBuffer中的数据写到outStream对象中
outStream.write(msgBuffer);
}
} catch (IOException e) {
Log.e("error", "ON RESUME: Exception during write.", e);
return "发送失败";
}
}
return "发送成功";
}
}
//更新界面的Handler类
class MyHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch(msg.what){
case 1:
//显示接收的信息
// etReceived.setText(ReceiveData);
break;
}
}
}
//回调接口
public interface OnConnectListener{
//连接成功
void onConnectSuccess(int[] msg);
//连接异常信息
void onConnectFailed(Exception e);
}
public OnConnectListener getOnConnectListener() {
return onConnectListener;
}
public void setOnConnectListener(OnConnectListener onConnectListener) {
this.onConnectListener = onConnectListener;
}
}
使用
BluetoothUtil.get().getMsg("20:19:01:26:05:87", new BluetoothUtil.OnConnectListener() {
@Override
public void onConnectSuccess(int[] msg) {
}
@Override
public void onConnectFailed(Exception e) {
}
});