detect bluetooth Le devices in Android

后端 未结 4 2039
一向
一向 2021-02-06 07:24

I\'m a beginner in android app development. I\'ve tried reading the documentation but am getting nowhere (functions in Android\'s tutorial such as StartLeScan() hav

4条回答
  •  花落未央
    2021-02-06 07:41

    I also thought this problem for few hours and I found out the answer by searching the Official doc.
    You need to know 3 class and method ScanCallback,BluetoothLeScanner,ScanResult
    //my level is so low that I cannot post the link....
    You can see in the android developer web ,the web page would show Added in API level 21" on the right side.

    Here is my code , modified from these project

    //declare    
    private BluetoothLeScanner mBluetoothLeScanner;  
    mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
    
    //start and stop scan
    mBluetoothLeScanner.startScan(mScanCallback);
    mBluetoothLeScanner.stopScan(mScanCallback);
    
    //Scan call back function
    private ScanCallback mScanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
             super.onScanResult(callbackType, result);
             mLeDeviceListAdapter.addDevice(result.getDevice());
             mLeDeviceListAdapter.notifyDataSetChanged();
        }
    };
    

    my grandle:

    android {
        compileSdkVersion 22
        buildToolsVersion "22.0.1"
    
        defaultConfig {
            applicationId "com.polkapolka.bluetooth.le"
            minSdkVersion 21
            targetSdkVersion 22
        }
    
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
            }
        }
    }
    

    These code works well on my phone,which is API 21 Hope it help you.

提交回复
热议问题