Reputation: 1
I am trying to do a BLE application in android and I am unable to figure out why onLeScan() function is not being called.
private void scanLeDevice(final boolean enable) {
Log.d(Tag,"in scanLeDevice");
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
invalidateOptionsMenu();
}
}, SCAN_PERIOD);
Log.d(Tag,"Scanning Done");
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
invalidateOptionsMenu();
}
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
Log.e(Tag,"Scan device rssi is " + rssi);
runOnUiThread(new Runnable() {
@Override
public void run() {
mLeDeviceListAdapter.addDevice(device);
mLeDeviceListAdapter.notifyDataSetChanged();
}
});
}
};
Logcat:
01-22 15:34:02.449: D/MainActivity(32531): in scanLeDevice
01-22 15:34:02.449: D/MainActivity(32531): Scanning Done
01-22 15:34:02.449: D/BluetoothAdapter(32531): startLeScan(): null
01-22 15:34:02.453: D/BluetoothAdapter(32531): onClientRegistered() - status=0 clientIf=5
01-22 15:34:09.005: D/MainActivity(32531): in scanLeDevice
01-22 15:34:09.005: D/BluetoothAdapter(32531): stopLeScan()
Upvotes: 0
Views: 1473
Reputation: 3135
You need BOTH of the following permissions in your AndroidManifest.xml in order to scan for devices:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
Upvotes: 0
Reputation: 11
Check if you have this in your AndroidManifest.xml
file:
<service android:name=".bluetooth.BluetoothLeService" android:enabled="true" />
Also you should initialize the Bluetooth adapter through BluetoothManager
:
if (!mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(mContext, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
return false;
}
// Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
// BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager =
(BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
Upvotes: 1