Android Bluetooth蓝牙开发:发现Bluetooth蓝牙设备(1)

旧城等待, 2024-02-17 16:52 140阅读 0赞



Android Bluetooth蓝牙开发:发现Bluetooth蓝牙设备(1)

Android Bluetooth蓝牙作为设备,要与其他蓝牙设备互联,那么先决条件就是已经被发现,本文先简介Android Bluetooth蓝牙的发现。
(1)启动代码后,首先要检查是否设备是否支持蓝牙设备,如果设备自身就没有蓝牙设备,巧妇难为无米之炊,就不要再做无用功了,代码片段:

  1. mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  2. // 检查设备上是否支持蓝牙设备
  3. if (mBluetoothAdapter == null) {
  4. Log.d(tag, "Device does not support Bluetooth");
  5. // 不支持蓝牙设备,木法,巧妇难为无米之炊,退出!
  6. return;
  7. }

(2)如果设备上有蓝牙设备,但此时用户有可能没有打开蓝牙,那么此时代码应该启动一个系统调用,弹出系统打开蓝牙的对话框,让用户手动打开蓝牙设备,代码片段:

  1. // 如果用户的设备没有开启蓝牙,则弹出开启蓝牙设备的对话框,让用户开启蓝牙
  2. if (!mBluetoothAdapter.isEnabled()) {
  3. Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  4. startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
  5. // 接下去,在onActivityResult回调判断
  6. }

(3)一切就绪后(设备上有蓝牙硬件模块,切蓝牙已经打开),接下来就是发现周围的蓝牙设备了,要做的就是扫描。本身扫描蓝牙的代码很简单,就一句代码:BluetoothAdapter的startDiscovery(),startDiscovery()返回的一个是布尔值,此值为true时候仅仅表示Android系统已经启动蓝牙模块的扫描过程,这个扫描过程是一个异步的过程。为了得到扫描结果,在一个广播接收器中异步接收Android系统发送的扫描结果:

  1. // 广播接收发现蓝牙设备
  2. private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
  3. @Override
  4. public void onReceive(Context context, Intent intent) {
  5. String action = intent.getAction();
  6. if (BluetoothDevice.ACTION_FOUND.equals(action)) {
  7. BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  8. // 添加到ListView的Adapter中。
  9. mArrayAdapter.add("设备名字:" + device.getName() + "\n设备地址:" + device.getAddress());
  10. mArrayAdapter.notifyDataSetChanged();
  11. }
  12. }
  13. };

以上完整的全部代码(其实全部在一个MainActivity.java代码文件里面):

  1. package zhangphil.bluetooth;
  2. import android.app.ListActivity;
  3. import android.bluetooth.BluetoothAdapter;
  4. import android.bluetooth.BluetoothDevice;
  5. import android.content.BroadcastReceiver;
  6. import android.content.Context;
  7. import android.content.Intent;
  8. import android.content.IntentFilter;
  9. import android.os.Bundle;
  10. import android.util.Log;
  11. import android.view.Menu;
  12. import android.view.MenuItem;
  13. import android.widget.ArrayAdapter;
  14. public class MainActivity extends ListActivity {
  15. private final int REQUEST_ENABLE_BT = 0xa01;
  16. private final String tag = "zhangphil";
  17. private ArrayAdapter<String> mArrayAdapter;
  18. private BluetoothAdapter mBluetoothAdapter;
  19. // 广播接收发现蓝牙设备
  20. private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
  21. @Override
  22. public void onReceive(Context context, Intent intent) {
  23. String action = intent.getAction();
  24. if (BluetoothDevice.ACTION_FOUND.equals(action)) {
  25. BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  26. // 添加到ListView的Adapter中。
  27. mArrayAdapter.add("设备名字:" + device.getName() + "\n设备地址:" + device.getAddress());
  28. mArrayAdapter.notifyDataSetChanged();
  29. }
  30. }
  31. };
  32. @Override
  33. protected void onCreate(Bundle savedInstanceState) {
  34. super.onCreate(savedInstanceState);
  35. // 先初始化蓝牙设备
  36. // initBluetoothAdapter();
  37. // 注册广播接收器。接收蓝牙发现讯息
  38. IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
  39. registerReceiver(mReceiver, filter);
  40. mArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1);
  41. setListAdapter(mArrayAdapter);
  42. }
  43. private void initBluetoothAdapter() {
  44. mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  45. // 检查设备上是否支持蓝牙设备
  46. if (mBluetoothAdapter == null) {
  47. Log.d(tag, "Device does not support Bluetooth");
  48. // 不支持蓝牙设备,木法,巧妇难为无米之炊,退出!
  49. return;
  50. }
  51. // 如果用户的设备没有开启蓝牙,则弹出开启蓝牙设备的对话框,让用户开启蓝牙
  52. if (!mBluetoothAdapter.isEnabled()) {
  53. Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  54. startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
  55. // 接下去,在onActivityResult回调判断
  56. }
  57. }
  58. // 启动蓝牙发现...
  59. private void discoveringDevices() {
  60. if (mBluetoothAdapter == null)
  61. initBluetoothAdapter();
  62. if (mBluetoothAdapter.startDiscovery()) {
  63. Log.d(tag, "启动蓝牙扫描设备...");
  64. }
  65. }
  66. // 可选方法,非必需
  67. // 此方法使自身的蓝牙设备可以被其他蓝牙设备扫描到,
  68. // 注意时间阈值。0 - 3600 秒。0将一直保持可被发现、可被扫描状态,但会很消耗电力资源。
  69. // 通常设置时间为120秒。
  70. private void enablingDiscoverability() {
  71. Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
  72. // 0,自身设备始终可以被发现(意味着将十分消耗设备资源,如电源)
  73. // 第二个参数可设置的范围是0~3600秒,在此时间区间(窗口期)内可被发现
  74. // 任何不在此区间的值都将被自动设置成120秒。
  75. discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
  76. startActivity(discoverableIntent);
  77. }
  78. @Override
  79. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  80. super.onActivityResult(requestCode, resultCode, data);
  81. if (requestCode == REQUEST_ENABLE_BT) {
  82. if (resultCode == RESULT_OK) {
  83. Log.d(tag, "打开蓝牙成功!");
  84. }
  85. if (resultCode == RESULT_CANCELED) {
  86. Log.d(tag, "放弃打开蓝牙!");
  87. }
  88. } else {
  89. Log.d(tag, "打开蓝牙异常!");
  90. return;
  91. }
  92. }
  93. @Override
  94. public boolean onOptionsItemSelected(MenuItem item) {
  95. int id = item.getItemId();
  96. if (id == R.id.action_init) {
  97. initBluetoothAdapter();
  98. }
  99. if (id == R.id.action_discovering) {
  100. discoveringDevices();
  101. }
  102. // 可选,非必需,系统默认的是120秒内可被发现。
  103. if (id == R.id.action_enabling_discoverability) {
  104. enablingDiscoverability();
  105. }
  106. return super.onOptionsItemSelected(item);
  107. }
  108. @Override
  109. protected void onDestroy() {
  110. super.onDestroy();
  111. unregisterReceiver(mReceiver);
  112. }
  113. @Override
  114. public boolean onCreateOptionsMenu(Menu menu) {
  115. getMenuInflater().inflate(R.menu.main, menu);
  116. return true;
  117. }
  118. }

需要在Androidmanifest.xml添加蓝牙相关权限:

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

至于菜单中的menu选项,定义在res/menu/main.xml文件里面:

  1. <menu xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. tools:context="zhangphil.bluetooth.MainActivity" >
  4. <item
  5. android:id="@+id/action_init"
  6. android:orderInCategory="1"
  7. android:showAsAction="never"
  8. android:title="初始化蓝牙设备"/>
  9. <item
  10. android:id="@+id/action_discovering"
  11. android:orderInCategory="2"
  12. android:showAsAction="never"
  13. android:title="发现设备"/>
  14. <item
  15. android:id="@+id/action_enabling_discoverability"
  16. android:orderInCategory="3"
  17. android:showAsAction="never"
  18. android:title="使自身设备可被别人的蓝牙设备发现"/>
  19. </menu>

代码运行结果如图所示:

Center

发表评论

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

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

相关阅读