(Updated : Debug results ) I can detect Bluetooth devices on my android application ( Android Studio ) on older android phones but in new ones I can't

Viewed 35

I have the same version of code and I give the application all autorisations and permissions.. The app worked perfectly on Android 6.0.1 and Android 8 I have gave to app all needed permissions, But I can't detect Bluetooth devices on Android 10, the same problem on android 11.. given permissions : The Code of Scan Activity :

 import android.Manifest;
    import android.app.AlertDialog;
    import android.app.ListActivity;
    import android.bluetooth.BluetoothAdapter;
    import android.bluetooth.BluetoothDevice;
    import android.bluetooth.BluetoothGatt;
    import android.bluetooth.BluetoothManager;
    import android.bluetooth.le.BluetoothLeScanner;
    import android.bluetooth.le.ScanCallback;
    import android.bluetooth.le.ScanFilter;
    import android.bluetooth.le.ScanResult;
    import android.bluetooth.le.ScanSettings;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.content.pm.PackageManager;
    import android.location.LocationManager;
    import android.os.Build;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.ParcelUuid;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.ImageView;
    import android.widget.ListView;
    import android.widget.ProgressBar;
    import android.widget.TextView;
    import android.widget.Toast;
    import androidx.core.app.ActivityCompat;
    import com.atmel.blecommunicator.com.atmel.otau.utils.OTAUUtils;
    import com.atmel.wearable.commonutils.GattAttributes;
    import com.microchip.bluetooth.data.blesensorapp.util.Constants;
    import java.util.ArrayList;
    import java.util.List;
    public class DeviceScanActivity extends ListActivity {
        private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
        private static final int REQUEST_ENABLE_BT = 1;
        private static final int REQUEST_ENABLE_LOCATION = 1;
        private static final long SCAN_PERIOD = 15000;
        private List<ScanFilter> filters;
        private BluetoothLeScanner mBLEScanner;
        private BluetoothAdapter mBluetoothAdapter;
        private BluetoothGatt mGatt;
        private Handler mHandler;
        private LeDeviceListAdapter mLeDeviceListAdapter;
        private BluetoothAdapter.LeScanCallback mLeScanCallback;
        private List<Integer> mRSSIs;
        private ScanCallback mScanCallback;
        private List<ScanResult> mScanResults;
        private List<byte[]> mScanResultsDep;
        private boolean mScanning;
        private ScanSettings settings;
        ProgressBar someProgressBar;
        private final BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals("android.bluetooth.adapter.action.STATE_CHANGED") && intent.getIntExtra("android.bluetooth.adapter.extra.STATE", Integer.MIN_VALUE) == 10) {
                    DeviceScanActivity.this.mBluetoothStatus = true;
                    new AlertDialog.Builder(context).setTitle(R.string.app_name).setMessage(R.string.error_bluetooth_off).setIcon(R.mipmap.ic_launcher).setCancelable(false).setPositiveButton(17039379, new DialogInterface.OnClickListener() {    
                        public void onClick(DialogInterface dialogInterface, int i) {         DeviceScanActivity.this.startActivityForResult(new Intent("android.bluetooth.adapter.action.REQUEST_ENABLE"), 1);
                        }
                    }).setNegativeButton(17039369, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Toast.makeText(DeviceScanActivity.this, R.string.error_bluetooth_off, 0).show();
                            DeviceScanActivity.this.finish();
                        }
                    }).show();
                }
            }
        };
        private boolean mBluetoothStatus = false;
    @Override // android.app.Activity
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        requestWindowFeature(5);
        Log.d("MBD", "MBD onCreate DeviceScantActivity ");
        if (Build.VERSION.SDK_INT >= 23) {
            requestPermissions(new String[]{"android.permission.ACCESS_COARSE_LOCATION"}, 1);
        }
        this.mHandler = new Handler();
        BluetoothAdapter adapter = ((BluetoothManager) getSystemService("bluetooth")).getAdapter();
        this.mBluetoothAdapter = adapter;
        if (adapter == null) {
            Toast.makeText(this, (int) R.string.error_bluetooth_not_supported, 0).show();
            finish();
            return;
        }
        View inflate = getLayoutInflater().inflate(R.layout.list_header, (ViewGroup) getListView(), false);
        ((TextView) inflate.findViewById(R.id.listHeader)).setText(R.string.scan_header);
        getListView().addHeaderView(inflate, null, false);
        View inflate2 = getLayoutInflater().inflate(R.layout.list_subheader, (ViewGroup) getListView(), false);
        getListView().addFooterView(inflate2, null, false);
        this.someProgressBar = (ProgressBar) findViewById(R.id.progressBar);
    }
    @Override // android.app.Activity
    public void onRequestPermissionsResult(int i, String[] strArr, int[] iArr) {
        if (i == 1 && iArr[0] == 0) {
            LocationManager locationManager = (LocationManager) getSystemService("location");
            if (!locationManager.isProviderEnabled("gps") || !locationManager.isProviderEnabled("network")) {
                startActivity(new Intent("android.settings.LOCATION_SOURCE_SETTINGS"));
            }
        }
    }
    @Override // android.app.Activity
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        if (!this.mScanning) {
            menu.findItem(R.id.menu_stop).setVisible(false);
            menu.findItem(R.id.menu_scan).setVisible(true);
        } else {
            menu.findItem(R.id.menu_stop).setVisible(true);
            menu.findItem(R.id.menu_scan).setVisible(false);
        }
        return true;
    }
    @Override // android.app.Activity
    public boolean onOptionsItemSelected(MenuItem menuItem) {
        int itemId = menuItem.getItemId();
        if (itemId == R.id.menu_scan) {
            this.mLeDeviceListAdapter.clear();
            setListAdapter(this.mLeDeviceListAdapter);
            this.mRSSIs.clear();
            scanLeDevice(true);
        } else if (itemId == R.id.menu_stop) {
            scanLeDevice(false);
        }
        return true;
    }
    @Override // android.app.Activity
    public void onResume() {
        super.onResume();
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(4);
        this.mLeDeviceListAdapter = new LeDeviceListAdapter();
        this.mRSSIs = new ArrayList();
        if (Build.VERSION.SDK_INT < 21) {
            this.mScanResultsDep = new ArrayList();
        } else {
            this.mScanResults = new ArrayList();
        }
        setListAdapter(this.mLeDeviceListAdapter);
        getListView().setCacheColorHint(0);
        getListView().setBackgroundResource(R.drawable.anotherbackground);
    }

    @Override // android.app.Activity
    public void onActivityResult(int i, int i2, Intent intent) {
        if (i == 1 && i2 == 0) {
            Toast.makeText(this, (int) R.string.error_bluetooth_off, 0).show();
            finish();
            return;
        }
        super.onActivityResult(i, i2, intent);
    }
    @Override // android.app.Activity
    public void onStart() {
        super.onStart();
        setLECallbacks();
        registerReceiver(this.bluetoothReceiver, new IntentFilter("android.bluetooth.adapter.action.STATE_CHANGED"));
        BluetoothAdapter bluetoothAdapter = this.mBluetoothAdapter;
        if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
            if (Build.VERSION.SDK_INT >= 21) {
                this.mBLEScanner = this.mBluetoothAdapter.getBluetoothLeScanner();
                this.settings = new ScanSettings.Builder().setScanMode(2).setCallbackType(1).build();
                ParcelUuid.fromString(GattAttributes.ENVIRONMENT_SERVICE);
                ScanFilter build = new ScanFilter.Builder().setManufacturerData(205, new byte[]{-2, OTAUUtils.AT_OTAU_IMAGE_END_NOTIFY_RESP, -83, 17, -49, Constants.BLE_SENSOR_RGB_LED_STATUS_UPDATE, 6, 63, 17, -27, -66, 62, 0, 2, com.microchip.zigbeeprovisioning.util.Constants.BLE_ZIGBEE_GET_CHANNEL_MAP_RESPONSE, -43, -59}).build();
                ArrayList arrayList = new ArrayList();
                this.filters = arrayList;
                arrayList.add(build);
            }
            scanLeDevice(true);
        } else if (!this.mBluetoothAdapter.isEnabled() && !this.mBluetoothStatus) {
            startActivityForResult(new Intent("android.bluetooth.adapter.action.REQUEST_ENABLE"), 1);
        }
    }

    @Override // android.app.Activity
    public void onPause() {
        super.onPause();
    }

    @Override // android.app.Activity
    public void onStop() {
        super.onStop();
        if (this.mBluetoothAdapter.isEnabled()) {
            resetLECallbacks();
            scanLeDevice(false);
            this.mLeDeviceListAdapter.clear();
            this.mRSSIs.clear();
            unregisterReceiver(this.bluetoothReceiver);
        }
    }

    @Override // android.app.ListActivity, android.app.Activity
    public void onDestroy() {
        super.onDestroy();
    }

    @Override // android.app.ListActivity
    public void onListItemClick(ListView listView, View view, int i, long j) {
        int i2 = i - 1;
        BluetoothDevice device = this.mLeDeviceListAdapter.getDevice(i2);
        if (device != null) {
            Intent intent = new Intent(this, DeviceControlActivity.class);
            intent.putExtra("DEVICE_NAME", device.getName());
            intent.putExtra("DEVICE_ADDRESS", device.getAddress());
            if (Build.VERSION.SDK_INT < 21) {
                intent.putExtra("SCAN_RESULT", this.mScanResultsDep.get(i2));
            } else {
                intent.putExtra("SCAN_RESULT", this.mScanResults.get(i2));
            }
            if (this.mScanning) {
                if (Build.VERSION.SDK_INT < 21) {
                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return;
                    }
                    this.mBluetoothAdapter.stopLeScan(this.mLeScanCallback);
                } else {
                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return;
                    }
                    this.mBLEScanner.stopScan(this.mScanCallback);
                }
                this.mScanning = false;
            }
            startActivity(intent);
        }
    }

    private void scanLeDevice(boolean z) {
        if (z) {
            this.mHandler.postDelayed(new Runnable() { // from class: com.microchip.blesensorapp.DeviceScanActivity.2
                @Override // java.lang.Runnable
                public void run() {
                    if (DeviceScanActivity.this.mLeDeviceListAdapter.isEmpty() && DeviceScanActivity.this.mScanning) {
                        DeviceScanActivity.this.someProgressBar.setVisibility(8);
                        Toast.makeText(DeviceScanActivity.this, R.string.ble_scan_empty, 0).show();
                    }
                    DeviceScanActivity.this.mScanning = false;
                    if (DeviceScanActivity.this.mBluetoothAdapter.isEnabled()) {
                        if (Build.VERSION.SDK_INT < 21) {
                            if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
                                // TODO: Consider calling
                                //    ActivityCompat#requestPermissions
                                // here to request the missing permissions, and then overriding
                                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                //                                          int[] grantResults)
                                // to handle the case where the user grants the permission. See the documentation
                                // for ActivityCompat#requestPermissions for more details.
                                return;
                            }
                            DeviceScanActivity.this.mBluetoothAdapter.stopLeScan(DeviceScanActivity.this.mLeScanCallback);
                        } else {
                            DeviceScanActivity.this.mBLEScanner.stopScan(DeviceScanActivity.this.mScanCallback);
                        }
                        DeviceScanActivity.this.invalidateOptionsMenu();
                    }
                }
            }, SCAN_PERIOD);
            this.mScanning = true;
            if (Build.VERSION.SDK_INT < 21) {
                this.mBluetoothAdapter.startLeScan(this.mLeScanCallback);
            } else {
                this.mBLEScanner.startScan(this.filters, this.settings, this.mScanCallback);
            }
        } else {
            this.mScanning = false;
            if (this.mBluetoothAdapter.isEnabled()) {
                if (Build.VERSION.SDK_INT < 21) {
                    this.mBluetoothAdapter.stopLeScan(this.mLeScanCallback);
                } else {
                    this.mBLEScanner.stopScan(this.mScanCallback);
                }
            }
        }
        invalidateOptionsMenu();
    }

    public void OnClickbutton(View view) {
        this.mLeDeviceListAdapter.clear();
        setListAdapter(this.mLeDeviceListAdapter);
        this.mRSSIs.clear();
        scanLeDevice(true);
    }

    public void OnClickbuttonstop(View view) {
        scanLeDevice(false);
        this.someProgressBar.setVisibility(8);
    }


    public class LeDeviceListAdapter extends BaseAdapter {
        private LayoutInflater mInflator;
        private ArrayList<BluetoothDevice> mLeDevices = new ArrayList<>();
        public long getItemId(int i) {
            return (long) i;
        }
        public LeDeviceListAdapter() {
            this.mInflator = DeviceScanActivity.this.getLayoutInflater();
        }
        public void addDevice(BluetoothDevice bluetoothDevice, int i, ScanResult scanResult) {
            if (!this.mLeDevices.contains(bluetoothDevice)) {
                this.mLeDevices.add(bluetoothDevice);
                DeviceScanActivity.this.mRSSIs.add(Integer.valueOf(i));
                DeviceScanActivity.this.mScanResults.add(scanResult);
                return;
            }  DeviceScanActivity.this.mRSSIs.remove(this.mLeDevices.indexOf(bluetoothDevice));
            DeviceScanActivity.this.mRSSIs.add(this.mLeDevices.indexOf(bluetoothDevice), Integer.valueOf(i));
            DeviceScanActivity.this.mScanResults.remove(this.mLeDevices.indexOf(bluetoothDevice));
            DeviceScanActivity.this.mScanResults.add(this.mLeDevices.indexOf(bluetoothDevice), scanResult);
        }
            public void addDeviceDep(BluetoothDevice bluetoothDevice, int i, byte[] bArr) {
            if (!this.mLeDevices.contains(bluetoothDevice)) {
                this.mLeDevices.add(bluetoothDevice);
                DeviceScanActivity.this.mRSSIs.add(Integer.valueOf(i));
                DeviceScanActivity.this.mScanResultsDep.add(bArr);
                return;
            }
DeviceScanActivity.this.mRSSIs.remove(this.mLeDevices.indexOf(bluetoothDevice));
                DeviceScanActivity.this.mRSSIs.add(this.mLeDevices.indexOf(bluetoothDevice), Integer.valueOf(i));
                DeviceScanActivity.this.mScanResultsDep.remove(this.mLeDevices.indexOf(bluetoothDevice));
                DeviceScanActivity.this.mScanResultsDep.add(this.mLeDevices.indexOf(bluetoothDevice), bArr);
            }
            public BluetoothDevice getDevice(int i) {
                return this.mLeDevices.get(i);
            }
            public void clear() {
                this.mLeDevices.clear();
            }

        @Override // android.widget.Adapter
        public int getCount() {
            return this.mLeDevices.size();
        }

        @Override // android.widget.Adapter
        public Object getItem(int i) {
            return this.mLeDevices.get(i);
        }

        @Override // android.widget.Adapter
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder viewHolder;
            if (view == null) {
                view = this.mInflator.inflate(R.layout.activity_device_scan, (ViewGroup) null);
                viewHolder = new ViewHolder();
                viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address);
                viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name);
                viewHolder.deviceRSSI = (TextView) view.findViewById(R.id.device_rssi);
                view.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) view.getTag();
            }
            BluetoothDevice bluetoothDevice = this.mLeDevices.get(i);
            if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                System.out.println("good");
            }
            String name = bluetoothDevice.getName();
            if (name == null || name.length() <= 0) {
                viewHolder.deviceName.setText(R.string.unknown_device);
            } else {
                viewHolder.deviceName.setText(name);
            }
            viewHolder.deviceAddress.setText(bluetoothDevice.getAddress());
            viewHolder.deviceRSSI.setText("RSSI: " + DeviceScanActivity.this.mRSSIs.get(i) + "dB");
            int intValue = ((Integer) DeviceScanActivity.this.mRSSIs.get(i)).intValue();
            if (intValue < -27 && intValue > -110) {
                if (intValue <= -27 && intValue > -60) {
                    ((ImageView) view.findViewById(R.id.image_rssi)).setImageResource(R.drawable.rssi_strength100);
                }
                if (intValue <= -60 && intValue > -70) {
                    ((ImageView) view.findViewById(R.id.image_rssi)).setImageResource(R.drawable.rssi_strength75);
                }
                if (intValue <= -70 && intValue > -80) {
                    ((ImageView) view.findViewById(R.id.image_rssi)).setImageResource(R.drawable.rssi_strength50);
                }
                if (intValue <= -80 && intValue > -90) {
                    ((ImageView) view.findViewById(R.id.image_rssi)).setImageResource(R.drawable.rssi_strength25);
                }
                if (intValue <= -90 && intValue > -110) {
                    ((ImageView) view.findViewById(R.id.image_rssi)).setImageResource(R.drawable.rssi_strength0);
                }
            } else {
                ((ImageView) view.findViewById(R.id.image_rssi)).setImageResource(R.drawable.rssi_strengthnil);
            }
            return view;
        }
    }

    private void setLECallbacks() {
        if (Build.VERSION.SDK_INT < 21) {
            this.mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
                /* class com.microchip.blesensorapp.DeviceScanActivity.AnonymousClass4 */

                public void onLeScan(final BluetoothDevice bluetoothDevice, final int i, final byte[] bArr) {
                    DeviceScanActivity.this.runOnUiThread(new Runnable() {
                        /* class com.microchip.blesensorapp.DeviceScanActivity.AnonymousClass4.AnonymousClass1 */

                        public void run() {
                            DeviceScanActivity.this.mLeDeviceListAdapter.addDeviceDep(bluetoothDevice, i, bArr);          DeviceScanActivity.this.mLeDeviceListAdapter.notifyDataSetChanged();
                        }
                    });
                }
            };
        } else {
            this.mScanCallback = new ScanCallback() {
                /* class com.microchip.blesensorapp.DeviceScanActivity.AnonymousClass5 */

                @Override // android.bluetooth.le.ScanCallback
                public void onBatchScanResults(List<ScanResult> list) {
                }

                public void onScanFailed(int i) {
                }

                public void onScanResult(int i, final ScanResult scanResult) {
                    DeviceScanActivity.this.runOnUiThread(new Runnable() {
                        /* class com.microchip.blesensorapp.DeviceScanActivity.AnonymousClass5.AnonymousClass1 */

                        public void run() {
                            DeviceScanActivity.this.mLeDeviceListAdapter.addDevice(scanResult.getDevice(), scanResult.getRssi(), scanResult);
                            DeviceScanActivity.this.mLeDeviceListAdapter.notifyDataSetChanged();
                        }
                    });
                }
            };
        }
    }

    public void resetLECallbacks() {
        this.mLeScanCallback = null;
    }
    static class ViewHolder {
        TextView deviceAddress;
        TextView deviceName;
        TextView deviceRSSI;

        ViewHolder() {
        }
    }
}

The build.gradle (targetSdk 32 and minSdk 23) contain this code and it works perfectly on android 8 and 6.0.1 :

plugins {
    id 'com.android.application'
}

android {
    compileSdk 32

    defaultConfig {
        applicationId "com.microchip.blesensorapp"
        minSdk 26
        targetSdk 32
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.4.2'
    implementation 'com.google.android.material:material:1.6.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

When I tryed to view the debugger to show the difference between the worked phone and the other i found :

The not worked one :

        I/BluetoothAdapter: STATE_ON
        D/BluetoothLeScanner: Start Scan with callback
        D/BluetoothLeScanner: onScannerRegistered() - status=0 scannerId=9 mScannerId=0
        D/Toast: show: caller = com.microchip.blesensorapp.DeviceScanActivity$2.run:282 
        I/Toast: show: focusDisplayId = 0, isFocusInDesktop = false mCustomDisplayId=-1 isDexDualMode=false
        I/Toast: show: isActivityContext = true
        I/BluetoothAdapter: STATE_ON
        D/BluetoothLeScanner: Stop Scan with callback

The worked one :

        D/BluetoothAdapter: STATE_ON
        D/BluetoothLeScanner: onClientRegistered() - status=0 clientIf=8
        W/ResourceType: For resource 0x7f0800bf, entry index(191) is beyond type entryCount(185)
        W/ResourceType: For resource 0x7f110238, entry index(568) is beyond type entryCount(490)
        W/ResourceType: For resource 0x7f0800bb, entry index(187) is beyond type entryCount(185)
0 Answers
Related