如何打开蓝牙
第一种方法:
直接调用系统对话框启动蓝牙:在AndroidManifest文件中添加需要的权限,高版本也不需要动态授权
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); //处理回调对话框 startActivityForResult(intent,1);
<uses-permission android:name="android.permission.BLUETOOTH"/>
第二种方法:
静默开启,不会有方法一的对话框:在AndroidManifest文件中添加需要的权限,步骤如下:
1)在AndroiManifest中配置需要的权限
2)对于6.0的运行时权限进行适配,在java中动态授权
3)最后直接调JavaSE开启
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); mBluetoothAdapter.enable();//开启 mBluetoothAdapter.disable();//关闭
No1:
搜索蓝牙设备
获取已配对设备: Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices(); 搜索周边设备未配对设备: mBtAdapter.startDiscovery();
No2:
通过广播接受者接收搜索结果。其中BluetoothDevice.ACTION_FOUND是找到一个设备
BluetoothAdapter.ACTION_DISCOVERY_FINISHED
No3:
根据地址获取设备:
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
No4:
获取设备socket,需要唯一的UUID:
device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
No5:
取消扫描设备,连接socket:端口
mAdapter.cancelDiscovery();
mmSocket.connect();