Android BLE not showing results - android

I am trying to scan for BLE devices around me. All i am getting is error code 2 and in some other occasions 'onBatchScanResults' returns empty list indefinitely. I am using redmi note 4 device. Thanks in advance.
My code :
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
final BluetoothLeScanner scanner = adapter.getBluetoothLeScanner();
final ScanSettings scanSettings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)
.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
.setMatchMode(ScanSettings.MATCH_MODE_STICKY)
.setNumOfMatches(ScanSettings.MATCH_NUM_MAX_ADVERTISEMENT)
.setReportDelay(1000L)
//.setLegacy(true)
.build();
btn_Scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e(TAG, "onClick: ");
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
if (scanner != null) {
Log.e(TAG, "scanner: ");
scanner.startScan(null, scanSettings, new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
Log.e(TAG, "onScanResult: " + result);
}
#Override
public void onBatchScanResults(List<ScanResult> results) {
super.onBatchScanResults(results);
Log.e(TAG, "onBatchScanResults: " + results);
}
#Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
Log.e(TAG, "onScanFailed: ### " + errorCode);
}
});
} else {
Log.e(TAG, "could not get scanner object");
}
}
});
thread.start();
}
});

Related

Android: How to get Bluetooth scanning status?

Here's how I start scanning BLE devices
if(bluetoothLeScanner!=null) {
bluetoothLeScanner.startScan(scanCallback);
isScanning = true;
}
How and when do I set isScanning to false?
Is there a way to find it inside of scanCallback?
private ScanCallback scanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, final ScanResult result) {
super.onScanResult(callbackType, result);
if(result==null) return;
runOnUiThread(new Runnable() {
#Override
public void run() {
bluetoothDeviceAdapter.update(result.getDevice());
bluetoothDeviceAdapter.notifyDataSetChanged();
}
});
// This doesn't mean end of scan does it?
// isScanning = false;
}
#Override
public void onBatchScanResults(List<ScanResult> results) {
super.onBatchScanResults(results);
final List<BluetoothDevice> deviceList = new ArrayList<>();
for(ScanResult result: results)
deviceList.add(result.getDevice());
runOnUiThread(new Runnable() {
#Override
public void run() {
bluetoothDeviceAdapter.updateBatch(deviceList);
bluetoothDeviceAdapter.notifyDataSetChanged();
}
});
// This doesn't mean end of scan does it?
// isScanning = false;
}
};
The scan runs until
You explicitly stop it.
The onScanFailed callback is called.
Bluetooth is turned off.

Trying to fetch a list of all my beacons nearby. but nothing is returned

I have all the permissions granted.
I use the beaconManager. which I create like this:
beaconManager = BeaconManager.getInstanceForApplication(this);
beaconManager.getBeaconParsers().add(new BeaconParser().
setBeaconLayout(BeaconParser.EDDYSTONE_UID_LAYOUT));
beaconManager.getBeaconParsers().add(new BeaconParser().
setBeaconLayout(BeaconParser.EDDYSTONE_TLM_LAYOUT));
beaconManager.getBeaconParsers().add(new BeaconParser().
setBeaconLayout(BeaconParser.EDDYSTONE_URL_LAYOUT));
beaconManager.bind(this);
OnBeaconConnect I do this:
#Override
public void onBeaconServiceConnect() {
ArrayList<Identifier> identifiers = new ArrayList<>();
// Set null to indicate that we want to match beacons with any value
identifiers.add(null);
// Represents a criteria of fields used to match beacon
try {
Region region = new Region("all-beacons-region", null, null, null);
Region region2 = new Region("de3be3ce-4770-477b-8893-0f0e5aeb9b98", null, null, null);
// Tells the BeaconService to start looking for beacons that match the passed Region object
beaconManager.startRangingBeaconsInRegion(region);
beaconManager.startRangingBeaconsInRegion(region2);
beaconManager.startMonitoringBeaconsInRegion(region);
beaconManager.startMonitoringBeaconsInRegion(region2);
} catch (RemoteException e) {
e.printStackTrace();
}
// Specifies a class that should be called each time the BeaconService gets ranging data, once per second by default
beaconManager.addRangeNotifier(this);
beaconManager.addMonitorNotifier(new MonitorNotifier() {
#Override
public void didEnterRegion(Region region) {
Log.i(TAG, "I just saw an beacon for the first time!");
}
#Override
public void didExitRegion(Region region) {
Log.i(TAG, "I no longer see an beacon");
}
#Override
public void didDetermineStateForRegion(int state, Region region) {
Log.i(TAG, "I have just switched from seeing/not seeing beacons: " + state);
}
});
}
And didRangeBeaconsInRegion has this:
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
if (beacons.size() > 0) {
Log.i(TAG, "The first beacon I see is about " + beacons.iterator().next().getDistance() + " meters away.");
}
}
But the monitorNotifier never gets called, and the rangeNotifier gets called, but beacons size is always 0.
Why don't I get the beacons here?
PS: I even tried hardcoding a beacon, using the UUID, but still I get nothing in monitorNotifier, and still size 0 in the range notifier
It looks to me like you set up three beacon parsers for the Eddystone formats, but you are trying to detect a beacon sending out the iBeacon format. (I say this based on the first identifier in the second region definition being a 16 byte UUID.) If this is indeed what you are trying to do, please add a beacon parser for the iBeacon format. You can find that here:
https://beaconlayout.wordpress.com/
Also, if you are trying to detect on Android 6+ make sure you have obtained location permissions otherwise you won't detect anything. See here:
https://altbeacon.github.io/android-beacon-library/requesting_permission.html
you can try this
public class BLEActivity extends ActionBarActivity {
private BluetoothAdapter mBluetoothAdapter;
private int REQUEST_ENABLE_BT = 1;
private Handler mHandler;
private static final long SCAN_PERIOD = 10000;
private BluetoothLeScanner mLEScanner;
private ScanSettings settings;
private List<ScanFilter> filters;
private BluetoothGatt mGatt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler = new Handler();
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, "BLE Not Supported",
Toast.LENGTH_SHORT).show();
finish();
}
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
}
#Override
protected void onResume() {
super.onResume();
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} else {
if (Build.VERSION.SDK_INT >= 21) {
mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
settings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build();
filters = new ArrayList<ScanFilter>();
}
scanLeDevice(true);
}
}
#Override
protected void onPause() {
super.onPause();
if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
scanLeDevice(false);
}
}
#Override
protected void onDestroy() {
if (mGatt == null) {
return;
}
mGatt.close();
mGatt = null;
super.onDestroy();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == Activity.RESULT_CANCELED) {
//Bluetooth not enabled.
finish();
return;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void scanLeDevice(final boolean enable) {
if (enable) {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
if (Build.VERSION.SDK_INT < 21) {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
} else {
mLEScanner.stopScan(mScanCallback);
}
}
}, SCAN_PERIOD);
if (Build.VERSION.SDK_INT < 21) {
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mLEScanner.startScan(filters, settings, mScanCallback);
}
} else {
if (Build.VERSION.SDK_INT < 21) {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
} else {
mLEScanner.stopScan(mScanCallback);
}
}
}
private ScanCallback mScanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
Log.i("callbackType", String.valueOf(callbackType));
Log.i("result", result.toString());
BluetoothDevice btDevice = result.getDevice();
connectToDevice(btDevice);
}
#Override
public void onBatchScanResults(List<ScanResult> results) {
for (ScanResult sr : results) {
Log.i("ScanResult - Results", sr.toString());
}
}
#Override
public void onScanFailed(int errorCode) {
Log.e("Scan Failed", "Error Code: " + errorCode);
}
};
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, int rssi,
byte[] scanRecord) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.i("onLeScan", device.toString());
connectToDevice(device);
}
});
}
};
public void connectToDevice(BluetoothDevice device) {
if (mGatt == null) {
mGatt = device.connectGatt(this, false, gattCallback);
scanLeDevice(false);// will stop after first device detection
}
}
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
Log.i("onConnectionStateChange", "Status: " + status);
switch (newState) {
case BluetoothProfile.STATE_CONNECTED:
Log.i("gattCallback", "STATE_CONNECTED");
gatt.discoverServices();
break;
case BluetoothProfile.STATE_DISCONNECTED:
Log.e("gattCallback", "STATE_DISCONNECTED");
break;
default:
Log.e("gattCallback", "STATE_OTHER");
}
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
List<BluetoothGattService> services = gatt.getServices();
Log.i("onServicesDiscovered", services.toString());
gatt.readCharacteristic(services.get(1).getCharacteristics().get
(0));
}
#Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic
characteristic, int status) {
Log.i("onCharacteristicRead", characteristic.toString());
gatt.disconnect();
}
};
}

No beep when using SCO for speech recognition (ANDROID)

I've put together a quick demo of a problem I'm having. When I run the following code, the text is read but there is no beep to prompt for STT and no double beep for the timeout (error 7) but it is running.
public class MainActivity extends AppCompatActivity {
private final String TAG = this.getClass().getSimpleName();
TextToSpeech oTTS;
HashMap<String, String> params = new HashMap<>();
String sTextToSpeak;
String sTextFromSpeech;
SpeechRecognizer sr;
Intent iSRIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final AudioManager tmpAm = (AudioManager) getApplicationContext()
.getSystemService(Context.AUDIO_SERVICE);
BroadcastReceiver scoBR = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String TAG = this.getClass().getSimpleName();
Log.i(TAG, "onReceive");
// SCO Connected
if (intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1) ==
AudioManager.SCO_AUDIO_STATE_CONNECTED) {
Log.i(TAG, "SCO Connected");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG, "Speaking:" + sTextToSpeak);
// TODO fix deprecation
//noinspection deprecation
oTTS.speak(sTextToSpeak, TextToSpeech.QUEUE_ADD, params);
}
// SCO Disconnected
if (intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1) ==
AudioManager.SCO_AUDIO_STATE_DISCONNECTED) {
Log.i(TAG, "SCO Disconnected");
}
}
};
// Start scoBroadcastReceiver
try {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
registerReceiver(scoBR, intentFilter);
Log.i(TAG, "SCOBroadcastReceiver registered");
} catch (Exception e) {
Log.i(TAG, "SCOBroadcastReceiver already registered");
}
oTTS = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
Log.i(TAG, "onInit called");
if (status == TextToSpeech.SUCCESS) {
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "utteranceId");
params.put(TextToSpeech.Engine.KEY_PARAM_STREAM,
String.valueOf(AudioManager.STREAM_VOICE_CALL));
Log.i(TAG, "TTS initialized");
Log.i(TAG, "Start SCO");
tmpAm.startBluetoothSco();
} else {
Log.i(TAG, "Couldn't initialize TTS");
}
}
});
oTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String s) {
Log.i(TAG, "UtteranceProgressListener onStart called");
}
#Override
public void onDone(String s) {
Log.i(TAG, "UtteranceProgressListener onDone called");
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.i(TAG, "Calling sr");
sr.startListening(iSRIntent);
}
});
}
#Override
public void onError(String s) {
Log.i(TAG, "UPL onError:" + s);
}
});
sTextToSpeak = "This is a test";
sr = SpeechRecognizer.createSpeechRecognizer(getApplicationContext());
sr.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
Log.i(TAG, "onReadyForSpeech");
}
#Override
public void onBeginningOfSpeech() {
Log.i(TAG, "onBeginningOfSpeech");
}
#Override
public void onRmsChanged(float rmsDb) {
//Log.i(TAG, "rmsDB:"+rmsDb);
}
#Override
public void onBufferReceived(byte[] buffer) {
Log.i(TAG, "onBufferReceived");
}
#Override
public void onEndOfSpeech() {
Log.i(TAG, "onEndOfSpeech");
}
#Override
public void onError(int error) {
Log.i(TAG, "onError:" + error);
tmpAm.stopBluetoothSco();
}
#Override
public void onResults(Bundle results) {
ArrayList data = results.getStringArrayList(
SpeechRecognizer.RESULTS_RECOGNITION);
if (data != null) {
sTextFromSpeech = data.get(0).toString();
} else {
sTextFromSpeech = "";
}
Log.i(TAG, "onResults:" + sTextFromSpeech);
tmpAm.stopBluetoothSco();
}
#Override
public void onPartialResults(Bundle bundle) {
Log.i(TAG, "onPartialResults:" + sTextFromSpeech);
tmpAm.stopBluetoothSco();
}
#Override
public void onEvent(int eventType, Bundle params) {
Log.i(TAG, "onEvent:" + eventType);
}
});
iSRIntent = new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
iSRIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
iSRIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
iSRIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak something...");
iSRIntent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
iSRIntent.putExtra("android.speech.extra.DICTATION_MODE", false);
iSRIntent.putExtra("android.speech.extra.MODE", 1);
iSRIntent.putExtra("android.speech.extra.PREFER_OFFLINE", false);
iSRIntent.putExtra("android.speech.extra.SUGGESTIONS_ENABLED", false);
iSRIntent.putExtra("android.speech.extra.PROFANITY_FILTER", true);
iSRIntent.putExtra("android.speech.extra.AUDIO_ENCODING_REQUESTED", false);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy called");
if (oTTS != null) {
oTTS.stop();
oTTS.shutdown();
}
}
}

how to show only timestamp, rssi and mac-address of beacon

private final ThreadLocal<ScanCallback> mScanCallback = new ThreadLocal<ScanCallback>() {
#Override
protected ScanCallback initialValue() {
return new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
ScanRecord btScanRecord = result.getScanRecord();
//Log.i(TAG,"new johoksdfjkhdfsj");//Not Called
if (btScanRecord != null) {
}
Connect();
//Log.i(TAG,"new johoksdfjkhdfsj");//Not Called
}
#Override
public void onBatchScanResults(List<ScanResult> results) {
for (ScanResult sr : results) {
Log.i("ScanResult-Results", sr.toString());
//Log.i(TAG, sr.toString());//not called
}
}
#Override
public void onScanFailed(int errorCode) {
Log.e("Scan Failed", "Error Code: " + errorCode);
}
};
}
};
I want only rssi, timestamp and mac-address but i think this code gives me some other string also like manufacturer details ,advertise flags etc.
try this BLE Scan listener:
public BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// also get address using
// device.getAddress();
addDevice(device,rssi);
String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
Log.e("In h:m:s"," "+currentDateTimeString);
Long tsLong = System.currentTimeMillis()/1000;
String ts = tsLong.toString();
Log.e("In miliseconds"," "+ts);
}
});
}
};
I hope this work.

BLE android 5.0 Crash

I have issues with android and BLE, any time i make a scan my app crash and i don't know the reason. I use startLeScan() can this be the reason?
Here is a sample of my code.
here is the place where I initialize for api 18
//API 18
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, int rssi,
byte[] scanRecord) {
Sensortag sensortag = new Sensortag(device, SensortagScanner.this,
mSensortagScannerCallback);
synchronized (this) {
for (Sensortag other : mDiscoveredDevices) {
if (sensortag.getName().equals(other.getName())) {
Log.i("SensortagScanner",
"Discovered duplicate device: "
+ other.getName());
return;
}
}
}
mDiscoveredDevices.add(sensortag);
Log.i("SensortagScanner",
"Discovered a device named " + device.getName() + ".");
mCallback.onSensorDiscovered(sensortag);
}
};
here is where i initialize ScanCall and what seems to be wrong looking the error java nulle exception
//API 21
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void initScanCallback() {
if (scanCallback != null)
return;
this.scanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
// Do whatever you want
}
#Override
public void onBatchScanResults(List<ScanResult> results) {
super.onBatchScanResults(results);
Log.d(TAG, "Batch scan results: ");
for (ScanResult result : results) {
Log.d(TAG, "Batch scan result: " + result.toString());
// Do whatever you want
}
}
#Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
// scanListener.onScanFinished();
Log.d(TAG, "Scan failed");
}
};
}
here is where i start the scan
#Override
public void startScan(SensorScannerCallback callback) {
mCallback = callback;
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
callback.onScannerUnavailable(this);
return;
}
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
stopScan();
}
}, SCAN_PERIOD);
Log.i("SensortagScanner", "Starting scan...");
mScanning = true;
// ////////////POUR API 21//////////////
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mBluetoothAdapter.getBluetoothLeScanner().startScan(scanCallback);
}
// /////////POUR API <18////////////////
else {
mBluetoothAdapter.startLeScan(mLeScanCallback);
}
}
try using the method for Android 5 like in the snippet below. It might help.
If it does not, please show more of your code and the error you have when the crash happens.
First, you need a callback, so initialize it correctly depending on the android version.
private void initScanCallback(){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
initCallbackLollipop();
}else{
initScanCallbackSupport();
}
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void initCallbackLollipop(){
if(scanCallback != null) return;
this.scanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
//Do whatever you want
}
#Override
public void onBatchScanResults(List<ScanResult> results) {
super.onBatchScanResults(results);
Log.d(TAG, "Batch scan results: ");
for (ScanResult result: results){
Log.d(TAG, "Batch scan result: " + result.toString());
//Do whatever you want
}
}
#Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
Log.d(TAG, "Scan failed");
}
};
}
private void initScanCallbackSupport(){
if(callback != null) return;
this.callback = new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, int rssi, final byte[] scanRecord) {
String address = device.toString();
String name = device.getName();
// parse uuids according to another stackoverflow post
//List<UUID> uuids = parseUuids(scanRecord);
// TODO Compare detected UUIDs with the uuidFilter
//for(UUID discUUID : uuids)
// for(UUID uuid : BLEScanService.this.uuidFilter)
// if(discUUID.equals(uuid))
BLEScanService.this.scanListener.onDeviceScanned(address, name, uuids, rssi);
}
};
}
Then you can start the scan according to the android version:
public void startScanWithServices(List<String> uuidFilters){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
scanLollipop(uuidFilters);
}else{
scanSupport(uuidFilters);
}
// Store filters for later filtering
int size = uuidFilters.size();
this.uuidFilter = new ArrayList<UUID>();
for(int i = 0; i<size; i++){
this.uuidFilter.add(UUID.fromString(uuidFilters.get(i)));
}
if(BuildConfig.DEBUG) Log.d(TAG, "BLE Scan started");
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void scanLollipop(List<String> uuidFilters){
if(scanCallback == null)
initCallbackLollipop();
List<ScanFilter> filters = new ArrayList<ScanFilter>();
ScanSettings settings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) // or BALANCED previously
.setReportDelay(0)
.build();
bluetoothAdapter.getBluetoothLeScanner().startScan(filters, settings, scanCallback);
//bluetoothAdapter.getBluetoothLeScanner().startScan(scanCallback);
}
private void scanSupport(List<String> uuidFilters){
if(callback == null)
initScanCallbackSupport();
//start scan
//boolean success = bluetoothAdapter.startLeScan(uuids, callback);
boolean success = bluetoothAdapter.startLeScan(callback);
//check scan success
if(!success) {
if(BuildConfig.DEBUG) Log.d(TAG, "BLE Scan failed");
scanListener.onScanFinished();
}
}
And then you can stop the scan like this:
public void stopScan(){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// Stop scan and flush pending scan
bluetoothAdapter.getBluetoothLeScanner().flushPendingScanResults(scanCallback);
bluetoothAdapter.getBluetoothLeScanner().stopScan(scanCallback);
}else{
bluetoothAdapter.stopLeScan(callback);
}
if(BuildConfig.DEBUG) Log.d(TAG, "BLE Scan stopted");
}
Check your manifest file. You should have these permissions
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

Categories

Resources