1.启用蓝牙并使设备处于可发现状态
2.连接启用蓝牙设备
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
/**
* 读写蓝牙设备
*
* @author hbbliyong
*
*/
public class BluetoothConnecion extends Thread {
private final BluetoothSocket mSocket;
private final InputStream mInStream;
private final OutputStream mOutStream;
byte[] buffer;
private final BluetoothAdapter mAdapter;
// 用于本应用程序唯一的UUID,
private static final UUID MY_UUID = UUID
.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
public BluetoothConnecion(BluetoothDevice device) {
BluetoothSocket tmp = null;
mAdapter = BluetoothAdapter.getDefaultAdapter();
// 获得用于指定蓝牙连接的BluetoothSocket
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (Exception e) {
e.printStackTrace();
}
mSocket = tmp;
// 在新线程中建立套接字连接,避免FC
Thread connectionThread = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
// 始终取消发现,因为它会降低连接的速度
mAdapter.cancelDiscovery();
// 建立到BluetoothSocket的连接
try {
// 这是一个阻塞调用,只在成功连接或者异常时返回
mSocket.connect();
} catch (Exception e) {
e.printStackTrace();
// 设备连接失败,关闭套接字
try {
mSocket.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
});
connectionThread.start();
InputStream tmpIn = null;
OutputStream tmpOut = null;
// 获得BluetoothSoket输入输出流
try {
tmpIn = mSocket.getInputStream();
tmpOut = mSocket.getOutputStream();
buffer = new byte[1024];
} catch (Exception e) {
e.printStackTrace();
}
mInStream = tmpIn;
mOutStream = tmpOut;
}
public void run() {
// 连接时保持监听InputStream
while (true) {
try {
// 从套接字流读取数据
mInStream.read(buffer);
// 向UI Activity发送获取的数据
} catch (Exception e) {
// TODO: handle exception
// 这里的异常标志着连接的丢失
// 向UI Activity发送获取的数据
break;
}
}
}
public void write(byte[] buffer)
{
try {
mOutStream.write(buffer);
} catch (Exception e) {
e.printStackTrace();
}
}
public void cancel()
{
try {
mSocket.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}