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:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- tools:context="zhangphil.bluetooth.MainActivity">
- <Button
- android:id="@+id/init"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Initialize Bluetooth device" />
- <Button
- android:id="@+id/discovery"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="devices detected" />
- <Button
- android:id="@+id/enable_discovery"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Make yourself discoverable to other Bluetooth devices" />
- <ListView
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:id="@+id/listView">
- </ListView>
- </LinearLayout>
Tested MainActivity.java:
- package zhangphil.bluetooth;
- import android.Manifest;
- import android.app.Activity;
- import android.bluetooth.BluetoothAdapter;
- import android.bluetooth.BluetoothDevice;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.content.IntentFilter;
- import android.content.pm.PackageManager;
- import android.os.Build;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.widget.ArrayAdapter;
- import android.widget.ListView;
- public class MainActivity extends Activity implements View.OnClickListener {
- private final int REQUEST_ENABLE_BT = 0xa01;
- private final int PERMISSION_REQUEST_COARSE_LOCATION = 0xb01;
- private String TAG = "zhangphil";
- private ArrayAdapter<String> mAdapter;
- private BluetoothAdapter mBluetoothAdapter;
- //Broadcast reception discovery Bluetooth device
- private BroadcastReceiver mReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- String action = intent.getAction();
- if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
- Log.d(TAG, "Start scanning...");
- }
- if (BluetoothDevice.ACTION_FOUND.equals(action)) {
- BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
- if (device != null) {
- //Adapter added to ListView.
- mAdapter.add("Device name:" + device.getName() + "\n Device address:" + device.getAddress());
- mAdapter.notifyDataSetChanged();
- }
- }
- if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
- Log.d(TAG, "Scan end.");
- }
- }
- };
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
- if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
- requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
- }
- }
- //Register the broadcast receiver.
- //Receive Bluetooth discovery
- IntentFilter filterFound = new IntentFilter(BluetoothDevice.ACTION_FOUND);
- registerReceiver(mReceiver, filterFound);
- IntentFilter filterStart = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
- registerReceiver(mReceiver, filterStart);
- IntentFilter filterFinish = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
- registerReceiver(mReceiver, filterFinish);
- mAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, android.R.id.text1);
- ((ListView) findViewById(R.id.listView)).setAdapter(mAdapter);
- findViewById(R.id.init).setOnClickListener(this);
- findViewById(R.id.discovery).setOnClickListener(this);
- findViewById(R.id.enable_discovery).setOnClickListener(this);
- }
- @Override
- public void onClick(View view) {
- switch (view.getId()) {
- case R.id.init:
- init();
- case R.id.discovery:
- discovery();
- case R.id.enable_discovery:
- enable_discovery();
- }
- }
- //Initialize Bluetooth device
- private void init() {
- mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
- //Check if the device supports Bluetooth devices
- if (mBluetoothAdapter == null) {
- Log.d(TAG, "Device does not support Bluetooth");
- //Bluetooth not supported, exit.
- return;
- }
- //If Bluetooth is not enabled on the user's device, a dialog box will pop up to enable Bluetooth
- if (!mBluetoothAdapter.isEnabled()) {
- Log.d(TAG, "Ask the user to turn on Bluetooth");
- Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
- startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
- //Next, judge in the onActivityResult callback
- }
- }
- //Start Bluetooth discovery
- private void discovery() {
- if (mBluetoothAdapter == null) {
- init();
- }
- mBluetoothAdapter.startDiscovery();
- }
- //Optional, not required
- //This method enables its own Bluetooth device to be scanned by other Bluetooth devices,
- //Note the time threshold. 0 - 3600 seconds.
- //The time is usually set to 120 seconds.
- private void enable_discovery() {
- Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
- //The second parameter can be set from 0 to 3600 seconds, which can be found in this time interval (window period)
- //Any value not in this range will be automatically set to 120 seconds.
- discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3600);
- startActivity(discoverableIntent);
- }
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- if (requestCode == REQUEST_ENABLE_BT) {
- if (resultCode == RESULT_OK) {
- Log.d(TAG, "Open Bluetooth successfully!");
- }
- if (resultCode == RESULT_CANCELED) {
- Log.d(TAG, "Give up Bluetooth!");
- }
- } else {
- Log.d(TAG, "Bluetooth is abnormal!");
- }
- }
- @Override
- protected void onDestroy() {
- super.onDestroy();
- unregisterReceiver(mReceiver);
- }
- @Override
- public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
- switch (requestCode) {
- case PERMISSION_REQUEST_COARSE_LOCATION:
- if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
- }
- break;
- }
- }
- }
Don't forget to add permissions:
- <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
- <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
- <uses-permission android:name="android.permission.BLUETOOTH" />
- <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
Code run result: