当前位置: 代码迷 >> 综合 >> 蓝牙相关知识总结
  详细解决方案

蓝牙相关知识总结

热度:77   发布时间:2024-02-02 02:52:28.0

一权限:

(1)定位权限
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

(2)蓝牙权限

    <uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED"/>

二:蓝牙状态

 //蓝牙状态
private void BluetoothState(){BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();if(bluetoothAdapter!=null){//设备支持蓝牙}else {//设备不支持蓝牙return;}//蓝牙是否是开启的boolean isOppenBluetooth = bluetoothAdapter.isEnabled();bluetoothAdapter.enable(); //开启蓝牙bluetoothAdapter.disable();//关闭蓝牙
}

三:扫描蓝牙设备

 //发起蓝牙设备扫描
private void startScanningBluetoothDevice(){BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();if(bluetoothAdapter!=null){if(bluetoothAdapter.isDiscovering()){bluetoothAdapter.cancelDiscovery(); //如果正处于扫描状态就先取消扫描}bluetoothAdapter.startDiscovery();}
}

四:接收扫描到的蓝牙设备

//广播接收器,接收扫描到的蓝牙设备
private BroadcastReceiver mReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();if(action.equals(BluetoothDevice.ACTION_FOUND)){BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);String name = device.getName();String address = device.getAddress();}else if(action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){//扫描过程结束,一般情况下一个扫描过程持续12秒左右}}
};//注册发起扫描的广播private void registeredBluetoothScanningBroadcast(){IntentFilter filter = new IntentFilter();filter.addAction(BluetoothDevice.ACTION_FOUND);filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);registerReceiver(mReceiver,filter);}

注:蓝牙扫描过程是耗时操作,并且扫描的结果返回是异步的所以广播机制来获取扫描到的蓝牙设备,接收到的结果是BluetoothDevice对象,通过该对象可以做一些简单的操作比如:发起配对请求,发起链接,发起断开等操作。

  相关解决方案