Bluetooth蓝牙简单总结
程序员文章站
2022-03-09 07:55:48
蓝牙蓝牙所需的权限启动蓝牙关闭蓝牙获取本机蓝牙信息扫描附近的蓝牙查看已配对蓝牙的设备蓝牙所需的权限
蓝牙所需的权限
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
启动蓝牙
Intent intent = new Intent();
intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);//启动蓝牙
intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);//被别人扫描到
startActivity(intent);
关闭蓝牙
//获得本机蓝牙设备
BluetoothAdapter defaultAdapter = BluetoothAdapter.getDefaultAdapter();
//关闭本机蓝牙设备
defaultAdapter.disable();
获取本机蓝牙信息
//首先先获取本机蓝牙设备
BluetoothAdapter defaultAdapter = BluetoothAdapter.getDefaultAdapter();
//获得本机蓝牙名称
String name = defaultAdapter.getName();
String address = defaultAdapter.getAddress();
扫描附近的蓝牙
//首先先获得自己的本机蓝牙适配器
BluetoothAdapter defaultAdapter = BluetoothAdapter.getDefaultAdapter();
//调用方法开始扫描
defaultAdapter.startDiscovery();//开始扫描
扫描到别的蓝牙设备后系统会发送广播,所以要有广播接收者
//广播接收者接受扫描到的蓝牙设备
class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(BluetoothDevice.ACTION_FOUND)){
//获得扫描到的远程设备
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
}
}
}
查看已配对蓝牙的设备
//获得本机蓝牙适配器对象
BluetoothAdapter defaultAdapter = BluetoothAdapter.getDefaultAdapter();
//调用方法获得已经配对的集合
Set<BluetoothDevice> bondedDevices = defaultAdapter.getBondedDevices();
for (BluetoothDevice bond: bondedDevices) {
Log.i("---","配对:"+bond.getName()+":"+bond.getAddress());
}
本文地址:https://blog.csdn.net/Ideal_of_life/article/details/107596600
下一篇: Android手机获取IP地址的两种方法