这是一种更健壮的方法,也可以处理enable()\disable()
方法的返回值:
public static boolean setBluetooth(boolean enable) {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
boolean isEnabled = bluetoothAdapter.isEnabled();
if (enable && !isEnabled) {
return bluetoothAdapter.enable();
}
else if(!enable && isEnabled) {
return bluetoothAdapter.disable();
}
// No need to change bluetooth state
return true;
}
并将以下权限添加到清单文件中:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
但是请记住以下要点:
这是一个异步调用:它将立即返回,并且客户端应侦听ACTION_STATE_CHANGED,以便随后的适配器状态更改得到通知。如果此调用返回true,则适配器状态将立即从STATE_OFF转换为STATE_TURNING_ON,并在一段时间后转换为STATE_OFF或STATE_ON。如果此调用返回false,则存在直接问题,该问题将阻止打开适配器-例如“飞行模式”,或者适配器已经打开。
更新:
好了,那么如何实现蓝牙监听器呢?
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR);
switch (state) {
case BluetoothAdapter.STATE_OFF:
// Bluetooth has been turned off;
break;
case BluetoothAdapter.STATE_TURNING_OFF:
// Bluetooth is turning off;
break;
case BluetoothAdapter.STATE_ON:
// Bluetooth is on
break;
case BluetoothAdapter.STATE_TURNING_ON:
// Bluetooth is turning on
break;
}
}
}
};
以及如何注册/注销接收者?(在您的Activity
课堂上)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
// Register for broadcasts on BluetoothAdapter state change
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mReceiver, filter);
}
@Override
public void onStop() {
super.onStop();
// ...
// Unregister broadcast listeners
unregisterReceiver(mReceiver);
}