Android Bluetooth蓝牙开发:Bluetooth蓝牙设备配对Paired Bluetooth Devices(2)

小鱼儿 2024-02-17 16:52 77阅读 0赞



Android Bluetooth蓝牙开发:Bluetooth蓝牙设备配对Paired Bluetooth Devices(2)

不同的Bluetooth进行配对时候,通常会显示如图所示的配对提示(前提是已经打开蓝牙设备且已经互相发现对方):
手机端:

Center

电脑端:

Center 1

图中所示例子是一个Android设备和一个PC(笔记本电脑)在进行蓝牙配对时候的对话。蓝牙设备在配对过程中,Android代码无法掌控,需要拥有该设备的用户手动操作完成配对过程。在配对完成后,Android上层Java代码即可遍历所有和当前设备已经配对的周围蓝牙设备。遍历代码比较简单:

  1. package zhangphil.bluetooth;
  2. import java.util.Set;
  3. import android.app.ListActivity;
  4. import android.bluetooth.BluetoothAdapter;
  5. import android.bluetooth.BluetoothDevice;
  6. import android.os.Bundle;
  7. import android.util.Log;
  8. public class MainActivity extends ListActivity {
  9. private BluetoothAdapter mBluetoothAdapter;
  10. @Override
  11. protected void onCreate(Bundle savedInstanceState) {
  12. super.onCreate(savedInstanceState);
  13. mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  14. // 获得和当前Android已经配对的蓝牙设备。
  15. Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
  16. if (pairedDevices.size() > 0) {
  17. // 遍历
  18. for (BluetoothDevice device : pairedDevices) {
  19. // 把已经取得配对的蓝牙设备名字和地址打印出来。
  20. Log.d("已经配对的蓝牙设备", device.getName() + " : " + device.getAddress());
  21. }
  22. }
  23. }
  24. }

配对完成,遍历已经配对的蓝牙设备,目的之一就是为了获得配对集合Set中的BluetoothDevice们,从中选取某一特定BluetoothDevice,从BluetoothDevice获得BluetoothSocket,取出输入输出流,进而进行数据传输。
从蓝牙配对集合中获取某一特定的BluetoothDevice进行数据传输,是Android蓝牙通信编程实现的其中一条途径,但并不是唯一途径。

蓝牙的权限:

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

附录文章:
1,《Android Bluetooth蓝牙开发:发现Bluetooth蓝牙设备(1)》链接地址:http://blog.csdn.net/zhangphil/article/details/50524809
2,Android Bluetooth蓝牙开发Google官方文档链接地址:http://developer.android.com/intl/zh-cn/guide/topics/connectivity/bluetooth.html

发表评论

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

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

相关阅读