簡述
在項(xiàng)目中也曾用到安卓藍(lán)牙饺鹃,主要是與藍(lán)牙模塊進(jìn)行通信,所以簡單的進(jìn)行總結(jié)崔拥,做下筆記,以備不時(shí)之需凤覆。
開啟與設(shè)置藍(lán)牙
獲取一個(gè)BluetoothAdapter链瓦,通過getDefaultAdapter()獲取默認(rèn)藍(lán)牙適配器或者自己指定。其次檢測藍(lán)牙是否打開,如若沒有打開慈俯,則通過適配器的.enable()開啟渤刃。還可以自定義藍(lán)牙設(shè)備的可見性以及其時(shí)間。
private void search() {
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (!adapter.isEnabled()) {
adapter.enable();
}
Intent enable = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
enable.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3600); //3600為藍(lán)牙設(shè)備可見時(shí)間
startActivity(enable);
Intent searchIntent = new Intent(this, ComminuteActivity.class);
startActivity(searchIntent);
}
搜索想要通信的設(shè)備
private class BluetoothReceiver extends 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);
if (isLock(device)) {
devices.add(device.getName());
}
deviceList.add(device);
}
showDevices();
}
}
private boolean isLock(BluetoothDevice device) {
boolean isLockName = (device.getName()).equals(lockName);
boolean isSingleDevice = devices.indexOf(device.getName()) == -1;
return isLockName && isSingleDevice;
}
并進(jìn)行連接
public void connect(final String message) {
Thread thread = new Thread(new Runnable() {
public void run() {
BluetoothSocket tmp = null;
Method method;
try {
method = device.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
tmp = (BluetoothSocket) method.invoke(device, 1);
} catch (Exception e) {
setState(CONNECT_FAILED);
Log.e("TAG", e.toString());
}
socket = tmp;
try {
socket.connect();
isConnect = true;
} catch (Exception e) {
setState(CONNECT_FAILED);
Log.e("TAG", e.toString());
}
}
}
在此前贴膘,記得調(diào)用bluetoothAdapter.startDiscovery();方法卖子。他會對其他藍(lán)牙設(shè)備進(jìn)行搜索,持續(xù)12秒刑峡,通過cancelDiscovery()取消洋闽。在搜索藍(lán)牙設(shè)備的過程中,系統(tǒng)可能會發(fā)送以下三個(gè)廣播:ACTION_DISCOVERY_START(開始搜索)突梦,ACTION_DISCOVERY_FINISHED(搜索結(jié)束)和ACTION_FOUND(找到設(shè)備)诫舅。ACTION_FOUND這個(gè)才是我們想要的,這個(gè)Intent中包含兩個(gè)extra fields:EXTRA_DEVICE和EXTRA_CLASS宫患,包含的分別是BluetoothDevice和BluetoothClass刊懈,BluetoothDevice中的EXTRA_DEVICE就是我們搜索到的設(shè)備對象。 確認(rèn)搜索到設(shè)備后娃闲,我們可以從得到的BluetoothDevice對象中獲得設(shè)備的名稱和地址虚汛。
連接設(shè)備之前需要uuid,用來配對畜吊,是一個(gè)128位的字符串id泽疆,用于表示。
注冊廣播與撤銷
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
receiver = new BluetoothReceiver();
registerReceiver(receiver, filter);
//撤銷
@Override
protected void onDestroy() {
unregisterReceiver(receiver);
super.onDestroy();
}
進(jìn)行通信
如果鏈接沒有問題玲献,就能夠進(jìn)行通信了殉疼。
if (isConnect) {
try {
OutputStream outStream = socket.getOutputStream();
outStream.write(getHexBytes(message));
} catch (IOException e) {
setState(WRITE_FAILED);
Log.e("TAG", e.toString());
}
try {
InputStream inputStream = socket.getInputStream();
int data;
while (true) {
try {
data = inputStream.read();
Message msg = handler.obtainMessage();
msg.what = DATA;
msg.arg1 = data;
handler.sendMessage(msg);
} catch (IOException e) {
setState(READ_FAILED);
Log.e("TAG", e.toString());
break;
}
}
} catch (IOException e) {
setState(WRITE_FAILED);
Log.e("TAG", e.toString());
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
Log.e("TAG", e.toString());
}
}
}
}
將字符串轉(zhuǎn)化為16進(jìn)制:
private byte[] getHexBytes(String message) {
int len = message.length() / 2;
char[] chars = message.toCharArray();
String[] hexStr = new String[len];
byte[] bytes = new byte[len];
for (int i = 0, j = 0; j < len; i += 2, j++) {
hexStr[j] = "" + chars[i] + chars[i + 1];
bytes[j] = (byte) Integer.parseInt(hexStr[j], 16);
}
return bytes;
}