建立蓝牙
前提是你的设备支持蓝牙。
如果支持,是自己的蓝牙打开。没有打开,可以在应用程序里打开蓝牙。
建立蓝牙需要两步:使用BluetoothAdapter。
1.得到BluetoothAdapter。使用getDefaultAdapter()方法,这个方法返回一个BluetoothAdapter,代表设备自己的蓝牙适配器。如果返回为空,那么设备不支持蓝牙,game over。
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAddapter();
if(nBluetoothAdapter == null){
//device does not support Bluetooth
}
2.打开蓝牙
首先,通过isEnabled()去判断蓝牙是否已经打开,如果返回值为false,那么蓝牙没有打开。
通过startActivityForResult()用ACTION_REQUEST_ENABLE。
例如:
if(!mBluetoothAdapter.isEnabled()){
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent,REQUEST_ENABLE_BT);
【REQUEST_ENABLE_BT必须要大于0】
如果打开蓝牙成功,在onActivityResult里得到RESULT_OK的返回值,如果失败,得到RESULT_CANCLED.
当然也可以监听ACTION_STATE_CHANGED.
EXTRA_STATE,EXTRA_PREVIOUS_STATE.
STATE_TURNING_ON,STATE_ON,STATE_TURNING_OFF,STATE_OFF