无法找到蓝牙LE设备

时间:2016-01-09 08:25:23

标签: android bluetooth android-bluetooth bluetooth-lowenergy

我正在做的项目是检测你周围的BLE设备。但是,该设备无法在附近找到任何BLE设备。设备支持BLE,但我的编码无法检测到BLE设备。如果有任何错误或遗漏,请帮助我。

public class MainActivity extends AppCompatActivity {

BluetoothLeScanner leScanner;
ArrayList<ScanFilter> scanFilters;
ScanSettings settings;
ProgressDialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button scanStartbtn= (Button) findViewById(R.id.startscanbtn);
    final BluetoothAdapter adapter=BluetoothAdapter.getDefaultAdapter();

    settings=new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
    scanFilters=new ArrayList<ScanFilter>();
    scanStartbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            leScanner=adapter.getBluetoothLeScanner();
            leScanner.startScan(scanFilters,settings,mScanCallback);
            Toast.makeText(MainActivity.this, "Scanning started", Toast.LENGTH_LONG).show();

        }
    });

}



ScanCallback mScanCallback=new ScanCallback() {
    @Override
    public void onScanResult(int callbackType, ScanResult result) {
        super.onScanResult(callbackType, result);
        Toast.makeText(MainActivity.this, "Hey I found BLE device+onScanResult" + result.toString(), Toast.LENGTH_LONG).show();
    }

    @Override
    public void onBatchScanResults(List<ScanResult> results) {
        super.onBatchScanResults(results);
        dialog.dismiss();
        for(ScanResult result:results) {
            Toast.makeText(MainActivity.this, "Hey I found BLE device" + result.toString(), Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onScanFailed(int errorCode) {
        super.onScanFailed(errorCode);

        if(errorCode==1) {
            Toast.makeText(MainActivity.this, "Scan is already started" + errorCode, Toast.LENGTH_LONG).show();
        }else if(errorCode==3)
        {
            Toast.makeText(MainActivity.this, "Scan is interrupted due to internal error" + errorCode, Toast.LENGTH_LONG).show();
        }else{
            Toast.makeText(MainActivity.this, "Unexpected error" + errorCode, Toast.LENGTH_LONG).show();
        }
    }
};
}

谢谢。

1 个答案:

答案 0 :(得分:0)

我认为以下代码就足够了:

final BluetoothAdapter adapter=BluetoothAdapter.getDefaultAdapter();
        adapter.startLeScan(new BluetoothAdapter.LeScanCallback() {
            @Override
            public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {

            }
        })