BluetoothAdapter用法
蓝牙运行原理:通过BluetoothAdapter蓝牙适配器处理任务,如果蓝牙被启动之后,系统会自动去搜索其它设备,如果匹配到附近的设备就发送一个广播,BroadcastRecevier的onReceive被调用一次,我们只需要在onReceive中处理自己的操作即可。
蓝牙是一种支持设备短距离传输数据的无线技术。android在2.0以后提供了这方面的支持。从查找蓝牙设备到能够相互通信要经过几个基本步骤(本机做为服务器):
根据需要设置自己的权限:
打开蓝牙的方法
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// if (bluetoothAdapter == null) {
// Toast.makeText(context,"对不起,您的设备不支持蓝牙,即将退出", Toast.LENGTH_SHORT).show();
// finish();
// } else if(!bluetoothAdapter.isEnabled()) {//蓝牙未开启
// Intent intent = newIntent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
// startActivityForResult(intent, REQUEST_BLUETOOTH_OPEN);
// }
设置蓝牙可见性的方法
1.通过Intent启动
private void ensureBluetoothDiscoverable() {
if(bluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE){
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3);
startActivity(intent);
}
}
2.通过系统setting强制开启
public void setDiscoverableTimeout(int timeout) { BluetoothAdapter adapter=BluetoothAdapter.getDefaultAdapter(); try { Method setDiscoverableTimeout = BluetoothAdapter.class.getMethod("setDiscoverableTimeout", int.class); setDiscoverableTimeout.setAccessible(true); Method setScanMode =BluetoothAdapter.class.getMethod("setScanMode", int.class,int.class); setScanMode.setAccessible(true); setDiscoverableTimeout.invoke(adapter, timeout); setScanMode.invoke(adapter, BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE,timeout); } catch (Exception e) { e.printStackTrace(); } }
第一种方法,让用户看到自己开启了蓝牙的可见性,第二种直接从后台开启蓝牙可见,但会一直可见下去,直到蓝牙关闭。我在小米miui + android6.0使用了第一种方法开启了蓝牙可见性,但并没有想象中的到时间自动关闭,因为这时的小米已经去掉了蓝牙可见性的计时关闭,只会一直开启下去,所以我找了好久,才找到下面的方法关闭了蓝牙可见性。
关闭蓝牙可见性
private void closeBluetoothDiscoverable(){
//尝试关闭蓝牙可见性
try {
Method setDiscoverableTimeout = BluetoothAdapter.class.getMethod("setDiscoverableTimeout&