Bluetooth adapter can't find Bluetooth device problem when startDiscovery is over Android 6.0 / 7.0 +

Keywords: Android xml encoding Java

Reprinted from: https://blog.csdn.net/zhangphil/article/details/77896924

Bluetooth adapter can't find Bluetooth device problem when startDiscovery is over Android 6.0 +


One of the important reasons for the problem is the permission problem of Android 6.0 +, Android 7.0 +. Good Bluetooth code running on Android 4.0 +, abnormal running on higher version. For example, the startDiscovery of Bluetooth adapter starts the Bluetooth discovery task, but it cannot discover Bluetooth devices. The solution is to increase the permission application for the latest version of Android system. Now let's give a complete example.

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.   
  9.     <Button  
  10.         android:id="@+id/init"  
  11.         android:layout_width="wrap_content"  
  12.         android:layout_height="wrap_content"  
  13.         android:text="Initialize Bluetooth device" />  
  14.   
  15.     <Button  
  16.         android:id="@+id/discovery"  
  17.         android:layout_width="wrap_content"  
  18.         android:layout_height="wrap_content"  
  19.         android:text="devices detected" />  
  20.   
  21.     <Button  
  22.         android:id="@+id/enable_discovery"  
  23.         android:layout_width="wrap_content"  
  24.         android:layout_height="wrap_content"  
  25.         android:text="Make yourself discoverable to other Bluetooth devices" />  
  26.   
  27.     <ListView  
  28.         android:layout_width="match_parent"  
  29.         android:layout_height="wrap_content"  
  30.         android:id="@+id/listView">  
  31.     </ListView>  
  32. </LinearLayout>  



Tested MainActivity.java:

  1. package zhangphil.bluetooth;  
  2.   
  3. import android.Manifest;  
  4. import android.app.Activity;  
  5. import android.bluetooth.BluetoothAdapter;  
  6. import android.bluetooth.BluetoothDevice;  
  7. import android.content.BroadcastReceiver;  
  8. import android.content.Context;  
  9. import android.content.Intent;  
  10. import android.content.IntentFilter;  
  11. import android.content.pm.PackageManager;  
  12. import android.os.Build;  
  13. import android.os.Bundle;  
  14. import android.util.Log;  
  15. import android.view.View;  
  16. import android.widget.ArrayAdapter;  
  17. import android.widget.ListView;  
  18.   
  19. public class MainActivity extends Activity implements View.OnClickListener {  
  20.     private final int REQUEST_ENABLE_BT = 0xa01;  
  21.     private final int PERMISSION_REQUEST_COARSE_LOCATION = 0xb01;  
  22.   
  23.     private String TAG = "zhangphil";  
  24.   
  25.     private ArrayAdapter<String> mAdapter;  
  26.     private BluetoothAdapter mBluetoothAdapter;  
  27.   
  28.     //Broadcast reception discovery Bluetooth device  
  29.     private BroadcastReceiver mReceiver = new BroadcastReceiver() {  
  30.   
  31.         @Override  
  32.         public void onReceive(Context context, Intent intent) {  
  33.             String action = intent.getAction();  
  34.   
  35.             if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {  
  36.                 Log.d(TAG, "Start scanning...");  
  37.             }  
  38.   
  39.             if (BluetoothDevice.ACTION_FOUND.equals(action)) {  
  40.                 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);  
  41.                 if (device != null) {  
  42.                     //Adapter added to ListView.  
  43.                     mAdapter.add("Device name:" + device.getName() + "\n Device address:" + device.getAddress());  
  44.                     mAdapter.notifyDataSetChanged();  
  45.                 }  
  46.             }  
  47.   
  48.             if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {  
  49.                 Log.d(TAG, "Scan end.");  
  50.             }  
  51.         }  
  52.     };  
  53.   
  54.     @Override  
  55.     protected void onCreate(Bundle savedInstanceState) {  
  56.         super.onCreate(savedInstanceState);  
  57.         setContentView(R.layout.activity_main);  
  58.   
  59.         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {  
  60.             if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {  
  61.                 requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);  
  62.             }  
  63.         }  
  64.   
  65.   
  66.         //Register the broadcast receiver.  
  67.         //Receive Bluetooth discovery  
  68.         IntentFilter filterFound = new IntentFilter(BluetoothDevice.ACTION_FOUND);  
  69.         registerReceiver(mReceiver, filterFound);  
  70.   
  71.         IntentFilter filterStart = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);  
  72.         registerReceiver(mReceiver, filterStart);  
  73.   
  74.         IntentFilter filterFinish = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);  
  75.         registerReceiver(mReceiver, filterFinish);  
  76.   
  77.         mAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, android.R.id.text1);  
  78.         ((ListView) findViewById(R.id.listView)).setAdapter(mAdapter);  
  79.   
  80.         findViewById(R.id.init).setOnClickListener(this);  
  81.         findViewById(R.id.discovery).setOnClickListener(this);  
  82.         findViewById(R.id.enable_discovery).setOnClickListener(this);  
  83.     }  
  84.   
  85.     @Override  
  86.     public void onClick(View view) {  
  87.         switch (view.getId()) {  
  88.             case R.id.init:  
  89.                 init();  
  90.   
  91.             case R.id.discovery:  
  92.                 discovery();  
  93.   
  94.             case R.id.enable_discovery:  
  95.                 enable_discovery();  
  96.         }  
  97.     }  
  98.   
  99.     //Initialize Bluetooth device  
  100.     private void init() {  
  101.         mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();  
  102.   
  103.         //Check if the device supports Bluetooth devices  
  104.         if (mBluetoothAdapter == null) {  
  105.             Log.d(TAG, "Device does not support Bluetooth");  
  106.   
  107.             //Bluetooth not supported, exit.  
  108.             return;  
  109.         }  
  110.   
  111.         //If Bluetooth is not enabled on the user's device, a dialog box will pop up to enable Bluetooth  
  112.         if (!mBluetoothAdapter.isEnabled()) {  
  113.             Log.d(TAG, "Ask the user to turn on Bluetooth");  
  114.   
  115.             Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);  
  116.             startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);  
  117.             //Next, judge in the onActivityResult callback  
  118.         }  
  119.     }  
  120.   
  121.     //Start Bluetooth discovery  
  122.     private void discovery() {  
  123.         if (mBluetoothAdapter == null) {  
  124.             init();  
  125.         }  
  126.   
  127.         mBluetoothAdapter.startDiscovery();  
  128.     }  
  129.   
  130.     //Optional, not required  
  131.     //This method enables its own Bluetooth device to be scanned by other Bluetooth devices,  
  132.     //Note the time threshold. 0 - 3600 seconds.  
  133.     //The time is usually set to 120 seconds.  
  134.     private void enable_discovery() {  
  135.         Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);  
  136.   
  137.         //The second parameter can be set from 0 to 3600 seconds, which can be found in this time interval (window period)  
  138.         //Any value not in this range will be automatically set to 120 seconds.  
  139.         discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3600);  
  140.   
  141.         startActivity(discoverableIntent);  
  142.     }  
  143.   
  144.     @Override  
  145.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  146.         super.onActivityResult(requestCode, resultCode, data);  
  147.   
  148.         if (requestCode == REQUEST_ENABLE_BT) {  
  149.             if (resultCode == RESULT_OK) {  
  150.                 Log.d(TAG, "Open Bluetooth successfully!");  
  151.             }  
  152.   
  153.             if (resultCode == RESULT_CANCELED) {  
  154.                 Log.d(TAG, "Give up Bluetooth!");  
  155.             }  
  156.   
  157.         } else {  
  158.             Log.d(TAG, "Bluetooth is abnormal!");  
  159.         }  
  160.     }  
  161.   
  162.     @Override  
  163.     protected void onDestroy() {  
  164.         super.onDestroy();  
  165.         unregisterReceiver(mReceiver);  
  166.     }  
  167.   
  168.   
  169.     @Override  
  170.     public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {  
  171.         switch (requestCode) {  
  172.             case PERMISSION_REQUEST_COARSE_LOCATION:  
  173.                 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {  
  174.   
  175.                 }  
  176.   
  177.                 break;  
  178.         }  
  179.     }  
  180. }  


Don't forget to add permissions:

  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" />  



Code run result:




Posted by literom on Tue, 31 Mar 2020 21:44:29 -0700