Skip to content

Instantly share code, notes, and snippets.

@Limuyang1013
Last active April 29, 2016 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Limuyang1013/47a4e0dc09e9b21c4dc900a8c6dc018a to your computer and use it in GitHub Desktop.
Save Limuyang1013/47a4e0dc09e9b21c4dc900a8c6dc018a to your computer and use it in GitHub Desktop.
public class BluetoothUtils {
/**
* 开启蓝牙
*
* @param v
*/
public static void startBluetooth(View v, Intent intent, Activity activity) {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter
.getDefaultAdapter();
if (bluetoothAdapter != null && !bluetoothAdapter.isEnabled()) {
bluetoothAdapter.enable();
intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
} else {
SnackBarUtils.showShort(v, "蓝牙已开启");
}
}
/**
* 关闭蓝牙
*
* @param v
*/
public static void stopBluetooth(View v) {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter
.getDefaultAdapter();
if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
bluetoothAdapter.disable();
SnackBarUtils.showShort(v, "蓝牙已关闭");
} else {
SnackBarUtils.showShort(v, "蓝牙未开启");
}
}
public static void unpairMac(String macToRemove) {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter
.getDefaultAdapter();
Set<BluetoothDevice> bondedDevices = bluetoothAdapter
.getBondedDevices();
try {
Class<?> btDeviceInstance = Class.forName(BluetoothDevice.class
.getCanonicalName());
Method removeBondMethod = btDeviceInstance.getMethod("removeBond");
boolean cleared = false;
for (BluetoothDevice bluetoothDevice : bondedDevices) {
String mac = bluetoothDevice.getAddress();
if (mac.equals(macToRemove)) {
removeBondMethod.invoke(bluetoothDevice);
Log.i("BT", "Cleared Pairing");
cleared = true;
break;
}
}
if (!cleared) {
Log.i("BT", "Not Paired");
}
} catch (Throwable th) {
Log.e("BT", "Error pairing", th);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment