public class BluetoothAdmin {
private BluetoothAdapter adapter;
private Context ctx;
public BluetoothAdmin(Context ctx) {
this.ctx = ctx;
adapter = BluetoothAdapter.getDefaultAdapter();
}
public boolean isOpen() {
return adapter.isEnabled();
}
public void open() {
adapter.enable();
}
public void close() {
adapter.disable();
}
public ArrayList<BluetoothDevice> getConnectedDevices() {
return new ArrayList(adapter.getBondedDevices());
}
public void unpairDevice(BluetoothDevice device) {
try {
Method m = device.getClass()
.getMethod("removeBond", (Class[]) null);
m.invoke(device, (Object[]) null);
} catch (Exception e) {
}
}
public void searchDevices() {
adapter.startDiscovery();
}
public void connect(BluetoothDevice device) throws IOException {
// 固定的UUID
ConnectThread connectBtThread = new ConnectThread(device.getAddress());
connectBtThread.start();
}
private class ConnectThread extends Thread {
String macAddress = "";
BluetoothSocket socket;
boolean connecting = false;
boolean connected = true;
BluetoothDevice mBluetoothDevice;
int connetTime;
public ConnectThread(String mac) {
macAddress = mac;
}
public void run() {
connecting = true;
connected = false;
if (adapter == null) {
adapter = BluetoothAdapter.getDefaultAdapter();
}
mBluetoothDevice = adapter.getRemoteDevice(macAddress);
adapter.cancelDiscovery();
final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
UUID uuid = UUID.fromString(SPP_UUID);
try {
socket = mBluetoothDevice.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
}
while (!connected && connetTime <= 3) {
connectDevice();
}
}
protected void connectDevice() {
try {
// 连接建立之前的先配对
if (mBluetoothDevice.getBondState() == BluetoothDevice.BOND_NONE) {
Method creMethod = BluetoothDevice.class
.getMethod("createBond");
creMethod.invoke(mBluetoothDevice);
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
adapter.cancelDiscovery();
try {
socket.connect();
connected = true;
} catch (Exception e) {
connetTime++;
connected = false;
try {
socket.close();
socket = null;
} catch (Exception e2) {
// TODO: handle exception
}
} finally {
connecting = false;
}
}
public void cancel() {
try {
socket.close();
socket = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
connecting = false;
}
}
}
}