我在蓝牙LE场景中扫描设备的代码无效。它运行正常,没有任何异常或错误。但onLeScan()函数(在leScanCallback中)根本没有调用,而其他蓝牙低功耗设备就在附近......
public class ScanBle extends Activity {
private BluetoothAdapter myAdapter;
private Handler bleHandler;
private long SCAN_PERIOD = 10000;
ArrayList<BluetoothDevice> allBleDevice;
ArrayAdapter<String> listAdaptor;
private String TagBle = "ScanBle";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BluetoothManager bm = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
myAdapter = bm.getAdapter();
listAdaptor = new ArrayAdapter<>(this, R.layout.activity_scan_ble);
allBleDevice = new ArrayList<BluetoothDevice>();
bleHandler = new Handler();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if(myAdapter == null || !myAdapter.isEnabled())
{
Intent enableBt = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBt);
finish();
return;
}
if(!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE))
{
Toast.makeText(getApplicationContext(), "No Le Feature", Toast.LENGTH_SHORT).show();
finish();
return;
}
startScan(true);
if(listAdaptor.getCount()>0)
{
ListView lv = new ListView(this);
lv.setAdapter(listAdaptor);
setContentView(lv);
}
else
{
Toast.makeText(this, "No Ble devices Found Bazingaaa", Toast.LENGTH_SHORT).show();
}
}
public void startScan(final boolean enable) {
Log.d(TagBle , "startScan() started");
// TODO Auto-generated method stub
if(enable)
{
Toast.makeText(getApplicationContext(), "Scan is running...", Toast.LENGTH_SHORT).show();
bleHandler.postDelayed(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
myAdapter.stopLeScan(callbackBle);
}
}, SCAN_PERIOD );
myAdapter.startLeScan(callbackBle);
}
else
{
myAdapter.stopLeScan(callbackBle);
}
}
public BluetoothAdapter.LeScanCallback callbackBle = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
// TODO Auto-generated method stub
Log.d(TagBle , "callBackBle() Running");
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
BluetoothDevice tempDevice = device;
allBleDevice.add(tempDevice);
listAdaptor.add(tempDevice.getName()+"\n"+tempDevice.getAddress());
}
});
}
};
}