Android蓝牙 打开 关闭 与 搜索

青旅半醒 2022-08-09 09:55 649阅读 0赞

Android蓝牙 打开 关闭 与 搜索

1.获取权限

  1. <manifest ... >
  2. <uses-permission android:name="android.permission.BLUETOOTH" />
  3. //普通权限,操作蓝牙时需要
  4. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
  5. //高级权限,配对等操作时需要
  6. </manifest>

2.打开和关闭蓝牙设备

  • 创建两个按钮,设置两个单击事件

  1. <Button
  2. android:layout_width="match_parent"
  3. android:layout_height="wrap_content"
  4. android:text="打开蓝牙"
  5. android:onClick="openBlueTooth"/>
  6. <Button
  7. android:layout_width="match_parent"
  8. android:layout_height="wrap_content"
  9. android:text="关闭蓝牙"
  10. android:onClick="closeBlueTooth"/>

  1. public void openBlueTooth(View view){
  2. // 打开蓝牙(提示对话框)
  3. Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
  4. discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
  5. startActivity(discoverableIntent);
  6. // 打开蓝牙(静默,无提示)
  7. // BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  8. // bluetoothAdapter.enable();//需要BLUETOOTH_ADMIN权限
  9. }
  10. public void closeBlueTooth(View view){
  11. // 关闭蓝牙
  12. BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  13. bluetoothAdapter.disable();
  14. }

3.搜索蓝牙设备

  • 新建个按钮

  1. <Button
  2. android:layout_width="match_parent"
  3. android:layout_height="wrap_content"
  4. android:text="搜索蓝牙"
  5. android:onClick="scanBlueTooth"/>
  • 添加方法

  1. public void scanBlueTooth(View view){
  2. BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  3. bluetoothAdapter.startDiscovery();
  4. // 返回值是个BluetoothDevice的Set集合
  5. Set<BluetoothDevice> bluetoothDevices = bluetoothAdapter.getBondedDevices();
  6. for(BluetoothDevice device : bluetoothDevices){
  7. System.out.println("Name: " + device.getName());
  8. System.out.println("Address: " + device.getAddress());
  9. }
  10. }

发表评论

表情:
评论列表 (有 0 条评论,649人围观)

还没有评论,来说两句吧...

相关阅读

    相关 android 文件

    利用android 传送文件需要解决一下几个问题。 1,发送方选中文件时如何获取文件地址?  以下这段代码作用是返回你选择文件的uri,因此你要重写 onActivityR