step1:获取蓝牙适配器
private BluetoothAdapter mBtAdapter; mBtAdapter=BluetoothAdapter.getDefaultAdapter();
step2:强制开启蓝牙设备
if(!mBtAdapter.isEnabled()){
mBtAdapter.enable();
}
step3:获取搜索/已连接的Device
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
或已经连接
private Set<BluetoothDevice>pairedDevices = mBtAdapter.getBondedDevices();
然后从该设备获取地址
mBtAddress = device.getAddress();
step5:根据搜索到的蓝牙设备的MAC地址,得到该设备
mBtDevice = mBtAdapter.getRemoteDevice(mBtAddress);
step6:开启客户端线程,线程里面完成了与SPP协议的连接
mBtClientConnectThread = new clientThread();
mBtClientConnectThread.start();
连接过程:(必须放在try中进行)
try {
//取消搜索设备的动作,否则接下来的设备连接会失败
mBtAdapter.cancelDiscovery();
//根据device获取socket
mBtSocket = mBtDevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
//连接socket
mBtSocket.connect();
} catch (IOException e) {
e.printStackTrace();
Log.e("connect", "", e);
Log.d("clientThread", "连接失败");
}
step7: 发送数据
try {
OutputStream mOutputStream = mBtSocket.getOutputStream();
mOutputStream.write(msg.getBytes()); //发送出去的值为:msg
mOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
step8: 清场
if(mBtClientConnectThread!=null)
{
mBtClientConnectThread.interrupt();
mBtClientConnectThread= null;
}
if (mBtSocket != null) {
try {
mBtSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mBtSocket = null;
}
};