当前位置:   article > 正文

BluetoothAdapter在Android6.0/7.0+以上startDiscovery不能发现蓝牙设备问题_startbluetoothdevicesdiscovery:ok 但无设备找到

startbluetoothdevicesdiscovery:ok 但无设备找到

BluetoothAdapter在Android6.0+以上startDiscovery不能发现蓝牙设备问题


问题的重要原因之一是Android 6.0+,Android 7.0+的权限问题引起的。在Android 4.0+上运行良好的蓝牙代码,在高版本运行异常。比如BluetoothAdapter的startDiscovery虽然启动了发现蓝牙任务,但是不能发现蓝牙设备。解决问题是针对最新高版本的Android系统增加权限申请。现在给出一个完整例子。

activity_main.xml:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:tools="http://schemas.android.com/tools"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent"
  6. android:orientation="vertical"
  7. tools:context="zhangphil.bluetooth.MainActivity">
  8. <Button
  9. android:id="@+id/init"
  10. android:layout_width="wrap_content"
  11. android:layout_height="wrap_content"
  12. android:text="初始化蓝牙设备" />
  13. <Button
  14. android:id="@+id/discovery"
  15. android:layout_width="wrap_content"
  16. android:layout_height="wrap_content"
  17. android:text="发现设备" />
  18. <Button
  19. android:id="@+id/enable_discovery"
  20. android:layout_width="wrap_content"
  21. android:layout_height="wrap_content"
  22. android:text="使自身可被其他蓝牙设备发现" />
  23. <ListView
  24. android:layout_width="match_parent"
  25. android:layout_height="wrap_content"
  26. android:id="@+id/listView">
  27. </ListView>
  28. </LinearLayout>



测试的MainActivity.java:

  1. package zhangphil.bluetooth;
  2. import android.Manifest;
  3. import android.app.Activity;
  4. import android.bluetooth.BluetoothAdapter;
  5. import android.bluetooth.BluetoothDevice;
  6. import android.content.BroadcastReceiver;
  7. import android.content.Context;
  8. import android.content.Intent;
  9. import android.content.IntentFilter;
  10. import android.content.pm.PackageManager;
  11. import android.os.Build;
  12. import android.os.Bundle;
  13. import android.util.Log;
  14. import android.view.View;
  15. import android.widget.ArrayAdapter;
  16. import android.widget.ListView;
  17. public class MainActivity extends Activity implements View.OnClickListener {
  18. private final int REQUEST_ENABLE_BT = 0xa01;
  19. private final int PERMISSION_REQUEST_COARSE_LOCATION = 0xb01;
  20. private String TAG = "zhangphil";
  21. private ArrayAdapter<String> mAdapter;
  22. private BluetoothAdapter mBluetoothAdapter;
  23. // 广播接收发现蓝牙设备
  24. private BroadcastReceiver mReceiver = new BroadcastReceiver() {
  25. @Override
  26. public void onReceive(Context context, Intent intent) {
  27. String action = intent.getAction();
  28. if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
  29. Log.d(TAG, "开始扫描...");
  30. }
  31. if (BluetoothDevice.ACTION_FOUND.equals(action)) {
  32. BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  33. if (device != null) {
  34. // 添加到ListView的Adapter。
  35. mAdapter.add("设备名:" + device.getName() + "\n设备地址:" + device.getAddress());
  36. mAdapter.notifyDataSetChanged();
  37. }
  38. }
  39. if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
  40. Log.d(TAG, "扫描结束.");
  41. }
  42. }
  43. };
  44. @Override
  45. protected void onCreate(Bundle savedInstanceState) {
  46. super.onCreate(savedInstanceState);
  47. setContentView(R.layout.activity_main);
  48. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  49. if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  50. requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
  51. }
  52. }
  53. // 注册广播接收器。
  54. // 接收蓝牙发现
  55. IntentFilter filterFound = new IntentFilter(BluetoothDevice.ACTION_FOUND);
  56. registerReceiver(mReceiver, filterFound);
  57. IntentFilter filterStart = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
  58. registerReceiver(mReceiver, filterStart);
  59. IntentFilter filterFinish = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
  60. registerReceiver(mReceiver, filterFinish);
  61. mAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, android.R.id.text1);
  62. ((ListView) findViewById(R.id.listView)).setAdapter(mAdapter);
  63. findViewById(R.id.init).setOnClickListener(this);
  64. findViewById(R.id.discovery).setOnClickListener(this);
  65. findViewById(R.id.enable_discovery).setOnClickListener(this);
  66. }
  67. @Override
  68. public void onClick(View view) {
  69. switch (view.getId()) {
  70. case R.id.init:
  71. init();
  72. case R.id.discovery:
  73. discovery();
  74. case R.id.enable_discovery:
  75. enable_discovery();
  76. }
  77. }
  78. // 初始化蓝牙设备
  79. private void init() {
  80. mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  81. // 检查设备是否支持蓝牙设备
  82. if (mBluetoothAdapter == null) {
  83. Log.d(TAG, "设备不支持蓝牙");
  84. // 不支持蓝牙,退出。
  85. return;
  86. }
  87. // 如果用户的设备没有开启蓝牙,则弹出开启蓝牙设备的对话框,让用户开启蓝牙
  88. if (!mBluetoothAdapter.isEnabled()) {
  89. Log.d(TAG, "请求用户打开蓝牙");
  90. Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  91. startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
  92. // 接下去,在onActivityResult回调判断
  93. }
  94. }
  95. // 启动蓝牙发现...
  96. private void discovery() {
  97. if (mBluetoothAdapter == null) {
  98. init();
  99. }
  100. mBluetoothAdapter.startDiscovery();
  101. }
  102. // 可选方法,非必需
  103. // 此方法使自身的蓝牙设备可以被其他蓝牙设备扫描到,
  104. // 注意时间阈值。0 - 3600 秒。
  105. // 通常设置时间为120秒。
  106. private void enable_discovery() {
  107. Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
  108. // 第二个参数可设置的范围是0~3600秒,在此时间区间(窗口期)内可被发现
  109. // 任何不在此区间的值都将被自动设置成120秒。
  110. discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3600);
  111. startActivity(discoverableIntent);
  112. }
  113. @Override
  114. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  115. super.onActivityResult(requestCode, resultCode, data);
  116. if (requestCode == REQUEST_ENABLE_BT) {
  117. if (resultCode == RESULT_OK) {
  118. Log.d(TAG, "打开蓝牙成功!");
  119. }
  120. if (resultCode == RESULT_CANCELED) {
  121. Log.d(TAG, "放弃打开蓝牙!");
  122. }
  123. } else {
  124. Log.d(TAG, "蓝牙异常!");
  125. }
  126. }
  127. @Override
  128. protected void onDestroy() {
  129. super.onDestroy();
  130. unregisterReceiver(mReceiver);
  131. }
  132. @Override
  133. public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
  134. switch (requestCode) {
  135. case PERMISSION_REQUEST_COARSE_LOCATION:
  136. if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  137. }
  138. break;
  139. }
  140. }
  141. }


不要忘记增加权限:

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



代码运行结果:



以上代码运行测试环境:硬件设备是三星S7Edge,Android版本:7.0

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/483866
推荐阅读
相关标签
  

闽ICP备14008679号