由于最近项目需要连接蓝牙,类似于智能手环连接蓝牙模块,网上找了些教程,有一些零零散散的程序,自己于是也写了一个能用,然后我发现谷歌有一个蓝牙的sample,一对比突然发现自己写的好low,不严谨。于是就直接 谷歌 例程,修改了部分。首先当初写的时候我有以下几个疑问。
1.如何实现又蓝牙又能接受数据,又能发送数据,这样不会冲突嘛?
2.UUID是啥,蓝牙模块的uuid又是啥?
3.网上程序有客户端又有服务器的蓝牙程序,那我app用的是哪个程序那,蓝牙模块那边不是app不能写程序又怎样?
4.app不断接受数据,我这边怎么判断为一整段数据,并拿来解析。因为在inputSteam.read()这里如果蓝牙没有数据收到的话会出现阻塞的情况,并且一段数据可能多次读取,并不会一次读取完
答案在文章底部揭晓,想直接看答案直接拉到最后。有耐心的可以先看下文,首先我们新建一个BluetoothService类,看看构造器先
public BluetoothChatService(Context context, Handler handler) {
mAdapter = BluetoothAdapter.getDefaultAdapter();
mState = STATE_NONE;//蓝牙状态
mHandler = handler;//用来更新ui
}
上面蓝牙状态分为3种,分别用来判断当前状态
public static final int STATE_NONE = 0; // we're doing nothing
public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
public static final int STATE_CONNECTED = 3; // now connected to a remote device
接下来就是connect()方法了。也就是启动连接
/**
* Start the ConnectThread to initiate a connection to a remote device.
*
* @param device The BluetoothDevice to connect
* @param secure Socket Security type - Secure (true) , Insecure (false)
*/
public synchronized void connect(BluetoothDevice device, boolean secure) {
// 取消之前线程,假设之前有打开过线程
if (mState == STATE_CONNECTING) {
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread =