在Android系统中,从Android 2.0的sdk就开始支持蓝牙开发,到现在蓝牙协议已经发生了从1.0-4.2的变化,开发的过程也发生了不少的变化。这次我主要介绍蓝牙2.0开发。
Android中蓝牙2.0开发分为步骤包括
- 在AndroidMainfilest.xml文件中进行权限配置,具体权限如下
<!-- 允许程序链接到以配对的蓝牙设备 -->
<uses-permission android:name="android.permission.BLUETOOTH" />
<!-- 打开搜索蓝牙权限 -->
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
2. 得到蓝牙适配器
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();// 获取蓝牙适配器
3. 打开蓝牙
if(!mAdapter.isEnabled()){
Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enabler, REQUEST_ENABLE)
}
4.加入搜索的结果的广播
// 增加过滤器
filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);// 远程设备发现动作。
// filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//
// 远程设备的键态的变化动作。
// filter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);//
// 蓝牙扫描本地适配器模改变动作。
// filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);// 状态改变动作
filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
// 发送广播
registerReceiver(receiver, filter);
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice bluetoothDevice = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (bluetoothDevice.getBondState() != BluetoothDevice.BOND_BONDED) {
Map<String, Object> haspmap = new HashMap<>();
haspmap.put(blueName, bluetoothDevice.getName());
haspmap.put(blueMac, bluetoothDevice.getAddress());
haspmap.put(bluePaired, "");
int j = 1;
for (int i = 0; i < mPairedList.size(); i++) {
/*
* String name = mPairedList.get(i).get(blueName)
* .toString();
*/
String mac = (String) mPairedList.get(i).get(blueMac);
if (!TextUtils.equals(mac, bluetoothDevice.getAddress())) {
continue;
}
j = 0;
}
if (j != 0) {
mPairedList.add(haspmap);
}
mPairedDeviceAdapter.notifyDataSetChanged();
}
// 结束
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
seekAnimImageView.clearAnimation();
seekAnimImageView.setVisibility(View.GONE);
isflag = false;
if (mPairedDeviceAdapter.getCount() == 0) {
no_paired_devices.setText(R.string.no_paired_device);
}
} else if (!BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
if (!BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
BluetoothDevice bluetoothDevice = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (devicesBluetoothDevices.size() <= 0) {
no_paired_devices.setText(R.string.no_paired_device);
} else {
// mPairedList.clear();
for (BluetoothDevice iterable : devicesBluetoothDevices) {
Map<String, Object> haspmap = new HashMap<>();
haspmap.put(blueName, iterable.getName());
haspmap.put(blueMac, iterable.getAddress());
if (!bluetoothDevice.getAddress().equals(iterable.getAddress())) {
haspmap.put(bluePaired, context.getString(R.string.paired));
mPairedList.add(haspmap);
} else if (flag) {
haspmap.put(bluePaired, context.getString(R.string.connected));
mPairedList.add(0, haspmap);
}
}
mPairedDeviceAdapter.notifyDataSetChanged();
}
}
}
}
}
};
5. 搜索设备
if (adapter.isDiscovering()) {
adapter.cancelDiscovery();
adapter.startDiscovery();
} else {
adapter.startDiscovery();
}
6.链接设备
设备连接的UUID
private static final UUID MY_UUID_SECURE = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
客户端
//链接前首先将搜索记得关掉,这个会消耗资源的占用
a) 链接
BluetoothSocket mmSocket= device.createRfcommSocketToServiceRecord(CustomBluetoothManager.MY_UUID_SECURE);
if (!this.mmSocket.isConnected()) {
this.mmSocket.connect();
}
b)得到数据流
收数据一般是专门启动一个线程用于
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream
private final OutputStream mmOutStream;
private boolean isClose = false;
public ConnectedThread(BluetoothSocket socket, String socketType) {
// Log.d("BluetoothService", "create ConnectedThread: " +
// socketType);
this.mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
// Log.e("BluetoothService", "temp sockets not created", e);
}
this.mmInStream = tmpIn;
this.mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[512];
byte[] cmd = new byte[512];
int bytes = 0;
int index = 0;
while (!this.isClose)
try {
//得到数据流方法
bytes = this.mmInStream.read(buffer);
} catch{
}finally{
try {
this.isClose = true;
if (this.mmSocket != null) {
this.mmSocket.close();
}
} catch (IOException e) {
// Log.e("BluetoothService", "close() of connect socket failed",
// e);
Log.i("BluetoothSocket", "BluetoothSocket4");
}
}
}
//写入方法
public boolean write(byte[] buffer) {
try {
this.mmOutStream.write(buffer);
return true;
} catch (IOException e) {
// Log.e("BluetoothService", "Exception during write", e);
}
return false;
}
}