Android蓝牙开发(二)经典蓝牙消息传输实现
上篇文章中,我们主要介绍了蓝牙模块,传统/经典蓝牙模块BT和低功耗蓝牙BLE及其相关的API,不熟悉的可以查看Android蓝牙开发(一)蓝牙模块及核心API 进行了解。
本篇主要记录用到的经典蓝牙开发流程及连接通讯。
1. 开启蓝牙
蓝牙连接前,给与相关系统权限:
<!-- 使用蓝牙的权限 -->
<uses-permission android:name="android.permission.BLUETOOTH" />
<!-- 扫描蓝牙设备或者操作蓝牙设置 -->
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<!--模糊定位权限,仅作用于6.0+-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!--精准定位权限,仅作用于6.0+-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
安卓6.0以上系统要动态请求及获取开启GPS内容:
/**
* 检查GPS是否打开
*/
private boolean checkGPSIsOpen() {
LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
if (locationManager == null)
return false;
return locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER);
}
蓝牙核心对象获取,若获取对象为null则说明设备不支持蓝牙:
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
判断蓝牙是否开启,没有则开启:
//判断蓝牙是否开启
if (!mBluetoothAdapter.isEnabled()) {
//开启蓝牙,耗时,监听广播进行后续操作
mBluetoothAdapter.enable();
}
2.扫描蓝牙
蓝牙扫描:
mBluetoothAdapter.startDiscovery();
取消扫描:
mBluetoothAdapter.cancelDiscovery();
3.蓝牙状态监听
蓝牙监听广播,监听蓝牙开关,发现设备,扫描结束等状态,定义状态回调接口,进行对应操作,例如:监听到蓝牙开启后,进行设备扫描;发现设备后进行连接等。
/**
* 监听蓝牙广播-各种状态
*/
public class BluetoothReceiver extends BroadcastReceiver {
private static final String TAG = BluetoothReceiver.class.getSimpleName();
private final OnBluetoothReceiverListener mOnBluetoothReceiverListener;
public BluetoothReceiver(Context context,OnBluetoothReceiverListener onBluetoothReceiverListener) {
mOnBluetoothReceiverListener = onBluetoothReceiverListener;
context.registerReceiver(this,getBluetoothIntentFilter());
}
private IntentFilter getBluetoothIntentFilter() {
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);//蓝牙开关状态
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);//蓝牙开始搜索
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//蓝牙搜索结束
filter.addAction(BluetoothDevice.ACTION_FOUND);//蓝牙发现新设备(未配对的设备)
return filter;
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action == null) {
return;
}
Log.i(TAG, "===" + action);
BluetoothDevice dev = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (dev != null) {
Log.i(TAG, "BluetoothDevice: " + dev.getName() + ", " + dev.getAddress());
}
switch (action) {
case BluetoothAdapter.ACTION_STATE_CHANGED:
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
Log.i(TAG, "STATE: " + state);
if (mOnBluetoothReceiverListener != null) {
mOnBluetoothReceiverListener.onStateChanged(state);
}
break;
case BluetoothAdapter.ACTION_DISCOVERY_STARTED:
Log.i(TAG, "ACTION_DISCOVERY_STARTED ");
break;
case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
if (mOnBluetoothReceiverListener != null) {
mOnBluetoothReceiverListener.onScanFinish();
}
break;
case BluetoothDevice.ACTION_FOUND:
short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MAX_VALUE);
Log.i(TAG, "EXTRA_RSSI:" + rssi);
if (mOnBluetoothReceiverListener != null) {
mOnBluetoothReceiverListener.onDeviceFound(dev);
}
break;
default:
break;
}
}
public interface OnBluetoothReceiverListener {
/**
* 发现设备
*
* @param bluetoothDevice 蓝牙设备
*/
void onDeviceFound(BluetoothDevice bluetoothDevice);
/**
* 扫描结束
*/
void onScanFinish();
/**
* 蓝牙开启关闭状态
*
* @param state 状态
*/
void onStateChanged(int state);
}
}
4.通讯连接
客户端,与服务端建立长连接,进行通讯:
/**
* 客户端,与服务端建立长连接
*/
public class BluetoothClient extends BaseBluetooth {
public BluetoothClient(BTListener BTListener) {
super(BTListener);
}
/**
* 与远端设备建立长连接
*
* @param bluetoothDevice 远端设备
*/
public void connect(BluetoothDevice bluetoothDevice) {
close();
try {
// final BluetoothSocket socket = bluetoothDevice.createRfcommSocketToServiceRecord(SPP_UUID); //加密传输,Android强制执行配对,弹窗显示配对码
final BluetoothSocket socket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(SPP_UUID); //明文传输(不安全),无需配对
// 开启子线程(必须在新线程中进行连接操作)
EXECUTOR.execute(new Runnable() {
@Override
public void run() {
//连接,并进行循环读取
loopRead(socket);
}
});
} catch (Throwable e) {
close();
}
}
}
服务端监听客户端发起的连接,进行接收及通讯:
/**
* 服务端监听和连接线程,只连接一个设备
*/
public class BluetoothServer extends BaseBluetooth {
private BluetoothServerSocket mSSocket;
public BluetoothServer(BTListener BTListener) {
super(BTListener);
listen();
}
/**
* 监听客户端发起的连接
*/
public void listen() {
try {
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
// mSSocket = adapter.listenUsingRfcommWithServiceRecord("BT", SPP_UUID); //加密传输,Android强制执行配对,弹窗显示配对码
mSSocket = adapter.listenUsingInsecureRfcommWithServiceRecord("BT", SPP_UUID); //明文传输(不安全),无需配对
// 开启子线程
EXECUTOR.execute(new Runnable() {
@Override
public void run() {
try {
BluetoothSocket socket = mSSocket.accept(); // 监听连接
mSSocket.close(); // 关闭监听,只连接一个设备
loopRead(socket); // 循环读取
} catch (Throwable e) {
close();
}
}
});
} catch (Throwable e) {
close();
}
}
@Override
public void close() {
super.close();
try {
mSSocket.close();
} catch (Throwable e) {
e.printStackTrace();
}
}
}
客户端连接及服务端监听基类,用于客户端和服务端之前Socket消息通讯,进行消息或文件的发送、接收,进行通讯关闭操作等:
public class BaseBluetooth {
public static final Executor EXECUTOR = Executors.newSingleThreadExecutor();
protected static final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //自定义
private static final String FILE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/bluetooth/";
private static final int FLAG_MSG = 0; //消息标记
private static final int FLAG_FILE = 1; //文件标记
private BluetoothSocket mSocket;
private DataOutputStream mOut;
private BTListener mBTListener;
private boolean isRead;
private boolean isSending;
public BaseBluetooth(BTListener BTListener) {
mBTListener = BTListener;
}
/**
* 循环读取对方数据(若没有数据,则阻塞等待)
*/
public void loopRead(BluetoothSocket socket) {
mSocket = socket;
try {
if (!mSocket.isConnected())
mSocket.connect();
notifyUI(BTListener.CONNECTED, mSocket.getRemoteDevice());
mOut = new DataOutputStream(mSocket.getOutputStream());
DataInputStream in = new DataInputStream(mSocket.getInputStream());
isRead = true;
while (isRead) { //循环读取
switch (in.readInt()) {
case FLAG_MSG: //读取短消息
String msg = in.readUTF();
notifyUI(BTListener.MSG_RECEIVED, msg);
break;
case FLAG_FILE: //读取文件
File file = new File(FILE_PATH);
if (!file.exists()) {
file.mkdirs();
}
String fileName = in.readUTF(); //文件名
long fileLen = in.readLong(); //文件长度
notifyUI(BTListener.MSG_RECEIVED, "正在接收文件(" + fileName + ")····················");
// 读取文件内容
long len = 0;
int r;
byte[] b = new byte[4 * 1024];
FileOutputStream out = new FileOutputStream(FILE_PATH + fileName);
while ((r = in.read(b)) != -1) {
out.write(b, 0, r);
len += r;
if (len >= fileLen)
break;
}
notifyUI(BTListener.MSG_RECEIVED, "文件接收完成(存放在:" + FILE_PATH + ")");
break;
}
}
} catch (Throwable e) {
close();
}
}
/**
* 发送短消息
*/
public void sendMsg(String msg) {
if (isSending || TextUtils.isEmpty(msg))
return;
isSending = true;
try {
mOut.writeInt(FLAG_MSG); //消息标记
mOut.writeUTF(msg);
} catch (Throwable e) {
close();
}
notifyUI(BTListener.MSG_SEND, "发送短消息:" + msg);
isSending = false;
}
/**
* 发送文件
*/
public void sendFile(final String filePath) {
if (isSending || TextUtils.isEmpty(filePath))
return;
isSending = true;
EXECUTOR.execute(new Runnable() {
@Override
public void run() {
try {
notifyUI(BTListener.MSG_SEND, "正在发送文件(" + filePath + ")····················");
FileInputStream in = new FileInputStream(filePath);
File file = new File(filePath);
mOut.writeInt(FLAG_FILE); //文件标记
mOut.writeUTF(file.getName()); //文件名
mOut.writeLong(file.length()); //文件长度
int r;
byte[] b = new byte[4 * 1024];
while ((r = in.read(b)) != -1) {
mOut.write(b, 0, r);
}
notifyUI(BTListener.MSG_SEND, "文件发送完成.");
} catch (Throwable e) {
close();
}
isSending = false;
}
});
}
/**
* 关闭Socket连接
*/
public void close() {
try {
isRead = false;
if (mSocket != null) {
mSocket.close();
notifyUI(BTListener.DISCONNECTED, null);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
/**
* 当前设备与指定设备是否连接
*/
public boolean isConnected(BluetoothDevice dev) {
boolean connected = (mSocket != null && mSocket.isConnected());
if (dev == null)
return connected;
return connected && mSocket.getRemoteDevice().equals(dev);
}
private void notifyUI(final int state, final Object obj) {
mBTListener.socketNotify(state, obj);
}
public interface BTListener {
int DISCONNECTED = 0;
int CONNECTED = 1;
int MSG_SEND = 2;
int MSG_RECEIVED = 3;
void socketNotify(int state, Object obj);
}
我这里只是简单记录了项目中用到的蓝牙通讯,两个设备之间不通过配对进行连接、通讯。
相关详细内容及使用请查看Github项目:https://github.com/MickJson/BluetoothCS
蓝牙配对操作及其它内容,可以详细查看我下面的参考资料,写的十分详细,比如设备通过MAC地址,可以通过BluetoothAdapter获取设备,再通过客户端connect方法去进行连接等。
BluetoothDevice btDev = mBluetoothAdapter.getRemoteDevice(address);
最后
连接中遇到问题:read failed, socket might closed or timeout, read ret: -1。
通过改UUID,反射等方法都还是会出现错误。连接时,要确保服务端及客户端都处于完全断开状态,否则连接就会出现以上问题,但偶尔还是会有问题,期待有什么好的方法可留言告诉我。
参考资料:
Android-经典蓝牙(BT)-建立长连接传输短消息和文件
欢迎点赞/评论,你们的赞同和鼓励是我写作的最大动力!
关注公众号:几圈年轮,查看更多有趣的技术资源。