Bluetooth LE devices not detected - android

My app needs to connect to a Bluetooth Low Energy device, and obviously the first step is to detect it. I have written the code bellow to do just that. When I run the app I have another BLE device (Xperia M2) beside my Dev phone (Huawei P8 Lite) with Bluetooth ON and discoverable, however, nothing get printed on the logcat. Is the device truly not being discovered or is the callback function not being called/malfunctioning. What can I do to identify which one of this situations is happening?
The scanBluetoothMethod is called elsewhere in the code.
private BluetoothManager bluetoothManager;
private BluetoothAdapter bluetoothAdapter;
private static final long SCAN_PERIOD = 10000;
private BluetoothLeScanner scanner;
private Handler scanHandler = new Handler();
private List<ScanFilter> scanFilters = new ArrayList<ScanFilter>();
private ScanSettings scanSettings;
private boolean scanRunning=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_pandlet);
...
bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
}
private void scanBluetoothLE() {
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
return;
}
progressDialog = new ProgressDialog(this);
progressDialog.setMessage(getString(R.string.addpandlet_searchingforbledevices));
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setIndeterminate(true);
progressDialog.setButton(DialogInterface.BUTTON_NEUTRAL, getString(R.string.addpandlet_cancelsearch), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
scanner.stopScan(scanCallback);
scanHandler.removeCallbacks(scanRunnable);
scanRunning = false;
return;
}
});
ScanSettings.Builder scanSettingsBuilder = new ScanSettings.Builder();
//scanSettingsBuilder.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES);
scanSettingsBuilder.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY);
scanSettings = scanSettingsBuilder.build();
scanHandler.post(scanRunnable);
}
private Runnable scanRunnable = new Runnable() {
#Override
public void run() {
scanner = BluetoothAdapter.getDefaultAdapter().getBluetoothLeScanner();
if (scanRunning) {
scanner.stopScan(scanCallback);
progressDialog.hide();
scanRunning = false;
} else {
scanRunning = true;
progressDialog.show();
scanHandler.postDelayed(this, SCAN_PERIOD);
scanner.startScan(scanFilters, scanSettings, scanCallback);
}
}
};
private ScanCallback scanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
System.out.println(result.getRssi() + " " + result.getDevice().getName() );
super.onScanResult(callbackType, result);
}
#Override
public void onScanFailed(int errorCode) {
System.out.println("Error code " + errorCode );
super.onScanFailed(errorCode);
}
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if( requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_OK )
scanBluetoothLE();
}

From the code - BluetoothAdapter.getDefaultAdapter().getBluetoothLeScanner(); it seems you are trying to scan bluetooth low energy devices..The device you are using I guess supports only classic bluetooth.
Try using devices which advertise bluetooth low energy services.You can build a app which advertise ble services on a device which supports bluetooth low energy.
Just to be sure, you can go to Settings->bluetooth and scan to check whether the device is being discovered by the default device bluetooth module.
Also you can check whether the device is detected by some other standard apps on playstore-https://play.google.com/store/apps/details?id=no.nordicsemi.android.mcp&hl=en

Related

Android BLE scan issue

I'me trying to create a simple BLE application on my Android phone.
I've tried a lot of example without success, i must forget something.
Hope you could help me.
First you'll find the permissions added and then my simple activy
Permissions:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
And my activity :
Two button, one to execute a Scan and another to stop it.
I'd like to detecte an BLE device, but nothing is never detected with my code.
public class MainActivity extends AppCompatActivity {
BluetoothManager btManager;
BluetoothAdapter btAdapter;
BluetoothLeScanner btScanner;
Button startScanningButton;
Button stopScanningButton;
TextView peripheralTextView;
private final static int REQUEST_ENABLE_BT = 1;
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
peripheralTextView = (TextView) findViewById(R.id.PeripheralTextView);
peripheralTextView.setMovementMethod(new ScrollingMovementMethod());
startScanningButton = (Button) findViewById(R.id.StartScanButton);
startScanningButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startScanning();
}
});
stopScanningButton = (Button) findViewById(R.id.StopScanButton);
stopScanningButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
stopScanning();
}
});
stopScanningButton.setVisibility(View.INVISIBLE);
btManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
btAdapter = BluetoothAdapter.getDefaultAdapter();
if ( btAdapter == null ) {
Toast.makeText(
this,
"Bluetooth not supported on this deveice",
Toast.LENGTH_LONG).show();
return;
}
btScanner = btAdapter.getBluetoothLeScanner();
btScanner = BluetoothAdapter.getDefaultAdapter().getBluetoothLeScanner();
// Ensures Bluetooth is available on the device and it is enabled. If not,
// displays a dialog requesting user permission to enable Bluetooth.
if (btAdapter == null || !btAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
if ( ! btAdapter.isEnabled() ) {
// Demande à activer l'interface bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
if ( checkSelfPermission( Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED ) {
requestPermissions(
new String[] { android.Manifest.permission.ACCESS_COARSE_LOCATION },
456 );
}
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
}
if (btAdapter != null && !btAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent,REQUEST_ENABLE_BT);
}
if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("This app needs location access");
builder.setMessage("Please grant location access so this app can detect peripherals.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
}
});
builder.show();
}
}
private ScanCallback leScanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
peripheralTextView.append("Device Name: " + result.getDevice().getName() + " rssi: " + result.getRssi() + "\n");
super.onScanResult(callbackType, result);
final int scrollAmount = peripheralTextView.getLayout().getLineTop(peripheralTextView.getLineCount()) - peripheralTextView.getHeight();
if (scrollAmount > 0)
peripheralTextView.scrollTo(0, scrollAmount);
}
};
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_COARSE_LOCATION: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
System.out.println("coarse location permission granted");
} else {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Functionality limited");
builder.setMessage("Since location access has not been granted, this app will not be able to discover beacons when in the background.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
}
});
builder.show();
}
return;
}
}
}
private boolean mScanning = false;
private Handler handler = new Handler();
private static final long SCAN_PERIOD = 30000;
public void startScanning() {
System.out.println("start scanning");
peripheralTextView.setText("");
startScanningButton.setVisibility(View.INVISIBLE);
stopScanningButton.setVisibility(View.VISIBLE);
if (!mScanning) {
// Stops scanning after a pre-defined scan period.
handler.postDelayed(new Runnable() {
#Override
public void run() {
mScanning = false;
btScanner.stopScan(leScanCallback);
System.out.println("stop scanning");
}
}, SCAN_PERIOD);
mScanning = true;
btScanner.startScan(leScanCallback);
System.out.println("restart scanning");
} else {
mScanning = false;
btScanner.stopScan(leScanCallback);
System.out.println("stop scanning");
}
}
public void stopScanning() {
System.out.println("stopping scanning");
peripheralTextView.append("Stopped Scanning");
startScanningButton.setVisibility(View.VISIBLE);
stopScanningButton.setVisibility(View.INVISIBLE);
AsyncTask.execute(new Runnable() {
#Override
public void run() {
btScanner.stopScan(leScanCallback);
}
});
}
}
I never scan nothing..
Totaly newby, thanks a lot for your help.
Regards
You also need to have ACCESS_BACKGROUND_LOCATION declared in order to find other Bluetooth devices. You can find more information here:-
https://developer.android.com/guide/topics/connectivity/bluetooth#Permissions
Bluetooth LE Scan fails in the background - permissions
Turn on Android LE scanning without asking user for permission
And the links below are useful for getting started with Android LE Development:-
The Ultimate Guide to Android BLE Development
Android Lollipop: Bluetooth LE Matures
Bluetooth LE Send String Data between Devices

Problem in scanning Bluetooth LE devices (no callback)

I am trying to develop an Android app capable to connect to a BLE device. But i have a problem to find ble devices. The scanLeDevice methods run but I have no callback. You can find my code below: I use Log.i() to display ble devices.
With another app (downloaded from the store) I can find my ble device and others bluetooth around. So It's not my phone's problem.
Thanks for help!
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter bluetoothAdapter;
private final int REQUEST_ENABLE_BT = 1;
private boolean mScanning;
// Stops scanning after 10 seconds.
private static final long SCAN_PERIOD = 10000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("MainActivity", "Begin");
// Initializes Bluetooth adapter.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
// Ensures Bluetooth is available on the device and it is enabled. If not,
// displays a dialog requesting user permission to enable Bluetooth.
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
Log.i("MainActivity", "End for permissions");
if(Build.VERSION.SDK_INT < 21){
scanLeDevice(true);
}else{
scanDevice(true);
}
}
private Handler handler = new Handler();
private void scanLeDevice(final boolean enable) {
if (enable) {
// Stops scanning after a pre-defined scan period.
handler.postDelayed(new Runnable() {
#Override
public void run() {
mScanning = false;
bluetoothAdapter.stopLeScan(leScanCallback);
}
}, SCAN_PERIOD);
mScanning = true;
bluetoothAdapter.startLeScan(leScanCallback);
Log.i("MainActivity", "scanning");
} else {
mScanning = false;
bluetoothAdapter.stopLeScan(leScanCallback);
}
}
// Device scan callback.
private BluetoothAdapter.LeScanCallback leScanCallback =
new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, int rssi,
byte[] scanRecord) {
runOnUiThread(new Runnable() {
#Override
public void run() {
//Ici///////////////////////////////////////
Log.i("MainActivity", "Nam: "+device.getName()+" Adresse: "+device.getAddress());
if(device.getName() != null && device.getName().equals("RN4871-85D7"))
scanLeDevice(false);
}
});
}
};
///////////////////Scan for API 21
private ScanSettings settings;
private List<ScanFilter> filters;
private BluetoothLeScanner mLEScanner;
private void scanDevice(final boolean enable){
if (mLEScanner==null){
mLEScanner = bluetoothAdapter.getBluetoothLeScanner();
settings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build();
filters = new ArrayList<ScanFilter>();
}
if (enable) {
if (mScanning) return;
// Stops scanning after a pre-defined scan period.
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (!mScanning) return;
try {
mScanning = false;
//Log.d("MainActivity","STOP SCAN AFTER DELAY");
mLEScanner.stopScan(mScanCallback);
Log.i("MainActivity", "stop scanning API 21");
} catch (Exception e){Log.e("MainActivity",e.getMessage());}
}
}, SCAN_PERIOD);
mScanning = true;
//Log.d("MainActivity","START SCAN FROM EXPLICIT CALL");
mLEScanner.startScan(filters, settings, mScanCallback);
Log.i("MainActivity", "scanning API 21");
} else if (mLEScanner!=null){
if (!mScanning) return;
mScanning = false;
try {
//Log.d("MainActivity","STOP SCAN FROM EXPLICIT CALL");
mLEScanner.stopScan(mScanCallback);
Log.i("MainActivity", "stop scanning API 21");
} catch (Exception e){Log.i("MainActivity",e.getMessage());}
}
}
//call back for API 21
//#TargetApi(21)
private ScanCallback mScanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
Log.i("MainActivity", "onScanResult API 21");
}
#Override
public void onBatchScanResults(List<ScanResult> results) {
super.onBatchScanResults(results);
Log.i("MainActivity", "onBatchScanResults API 21");
}
#Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
Log.i("MainActivity", "onScanFailed API 21");
}
};
}
Thanks for your help``
I found what was the problem about the location.
In fact, if you work with a API >= 23, you have to authorize you app to access to the location (not only in the Manifest file, but in you code it self).
So if you have the same problem:
First, manualy, go to your phon's setting and autorize your app to access to location: to be sure that was the problem.
Then add the code below so that, The application ask the user to authorize the application to access the location
/////////////////////////Location/////
#TargetApi(Build.VERSION_CODES.M)
private void loadPermissions(String perm,int requestCode) {
if (ContextCompat.checkSelfPermission(this, perm) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, perm)) {
ActivityCompat.requestPermissions(this, new String[]{perm},requestCode);
}
} else if (checkLocationEnabled())
initScanner();
}
private boolean checkLocationEnabled(){
LocationManager lm = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}
if(!gps_enabled && !network_enabled) {
// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage("GPS desabled");
dialog.setPositiveButton("Open GPS settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
//get gps
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
}
});
dialog.show();
return false;
} else return true;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// granted
if (checkLocationEnabled())
initScanner();
}
else{
// no granted
}
return;
}
}
}
I had this problem too because I was using ACCESS_COARSE_LOCATION on the permission.
When I changed to ACCESS_FINE_LOCATION, it finally works for me!

Bluetooth BLE ScanCallback stopped working

I am working on BLE devices android application. i am trying to get available bluetooth devices using scanCallBack. It was working fine some days ago but suddenly it stopped. onScanResults or onScanFailed nothing are NOT executing. I have given the ACCESS_COARSE_LOCATION, BLUETOOTH_ADMIN, BLUETOOTH and ACCESS_FINE_LOCATION in manifest and request permissions at run time also.Bluetooth is on and location is also on. Please help.
Measurement.java
public class MeasurementScreen extends AppCompatActivity {
private BluetoothAdapter bluetoothAdapter;
static int REQUEST_ENABLE_BT = 1001;
private Boolean spinnerStatus= false;
private Handler handler = new Handler(Looper.getMainLooper());
final BluetoothAdapter mBluetoothAdapter =
BluetoothAdapter.getDefaultAdapter();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.device_reading_screen);
Objects.requireNonNull(getSupportActionBar()).hide();
if (Build.VERSION.SDK_INT >= 23) {
int permissionCheck = ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION);
if (permissionCheck == -1 ) {
ActivityCompat.requestPermissions(this,
new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION
}, 0);
}
}
final Button tryAgain = findViewById(R.id.tryagain);
next = findViewById(R.id.next);
back = findViewById(R.id.back);
progressDialog = new ProgressDialog(this);
bluetoothscan();
}
void bluetoothscan(){
spinner();
scanBLEDevices(true);
}
private void scanBLEDevices(final boolean enable){
final BluetoothLeScanner bluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
final BLEScanCallback scanCallback = new BLEScanCallback();
if (enable){
// Stops scanning after a pre-defined scan period.
handler.postDelayed(new Runnable() {
#Override
public void run() {
mScanning = false;
bluetoothLeScanner.stopScan(scanCallback);
}
}, 10000);
mScanning = true;
bluetoothLeScanner.startScan(scanCallback);
}else{
mScanning = false;
bluetoothLeScanner.stopScan(scanCallback);
}
}
public class BLEScanCallback extends ScanCallback{
#Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
Log.e("Scan Success", "Scan Success");
}
#Override
public void onBatchScanResults(List<ScanResult> results) {
super.onBatchScanResults(results);
Log.e("Scan Success", "Scan Success Batch");
}
#Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
Log.e("Scan Failed", "Error Code: " + errorCode);
}
}
}
This is the log output:-
D/BluetoothAdapter: STATE_ON
D/BluetoothLeScanner: onClientRegistered() - status=0 clientIf=6
mClientIf=0

Android BLE device discover, connect & disconnect

Basically, I am an iOS developer. I have a requirement to scan, connect & disconnect BLE devices. Everything works fine in iOS. Then I tried the following code to scan in Android. None of the devices re scanned at anytime. Could anyone help me, if I am doing something wrong.
public class MainActivity extends AppCompatActivity {
BluetoothAdapter bluetoothAdapter;
TextView statusTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
statusTextView = (TextView)findViewById(R.id.statusTxtView);
}
#Override
protected void onStart() {
super.onStart();
enableBluetooth();
}
private void enableBluetooth() {
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
statusTextView.setText("BT disabled");
Intent enableBtIntent =
new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
} else {
statusTextView.setText("BT enabled");
}
boolean status = bluetoothAdapter.startDiscovery();
if (status == true) {
statusTextView.setText("Start scanning");
} else {
statusTextView.setText("Failed scanning");
}
}
BluetoothAdapter.LeScanCallback scanCallback = new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
statusTextView.setText(device.getName());
}
};
}
You've not started scanning. After starting bluetooth discovery using bluetoothAdapter.startDiscovery(), you have to start scanning in order to get scan results. Use the following code to start scan.
I've not tested it but it should work as follows:
BluetoothLeScanner scanner = bluetoothAdapter.getBluetoothLeScanner();
scanner.startScan(scanCallback);
where scanCallback is the above callback you have created but unused.
Make sure that you have BLUETOOTH_ADMIN permission.
First you have to scan device
#SuppressLint("NewApi")
private void turnonBLE() {
// TODO Auto-generated method stub
manager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
mBLEAdapter = manager.getAdapter();
mLeScanner = mBLEAdapter.getBluetoothLeScanner();
mBLEAdapter.enable();
scanLeDevice(true);
Toast.makeText(getApplicationContext(), "BTLE ON Service",
Toast.LENGTH_LONG).show();
Log.e("BLE_Scanner", "TurnOnBLE");
}
If you are not using any uuid then scan without uuid
public void scanLeDevice(final boolean enable) {
if (enable) {
if (Build.VERSION.SDK_INT < 21) {
mBLEAdapter.startLeScan(mLeScanCallback);
} else {
ParcelUuid uuid = ParcelUuid.fromString(UUIDList.SENSOR_MAIN_SERVICE_UUID_STRING.toString());
ScanFilter scanFilter = new ScanFilter.Builder().setServiceUuid(uuid).build();
ScanSettings settings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.setReportDelay(0)
.build();
if (mLeScanner != null)
mLeScanner.startScan(Collections.singletonList(scanFilter), settings, mScanCallback);
}
} else {
if (Build.VERSION.SDK_INT < 21) {
mBLEAdapter.stopLeScan(mLeScanCallback);
} else {
mLeScanner.stopScan(mScanCallback);
}
}
}
From that call scanCallback
private ScanCallback mScanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
BluetoothDevice btDevice = result.getDevice();
connectToDevice(btDevice, result.getScanRecord().getBytes());
}
#Override
public void onBatchScanResults(List<ScanResult> results) {
for (ScanResult sr : results) {
Log.e("ScanResult - Results", sr.toString());
}
}
#Override
public void onScanFailed(int errorCode) {
Log.e("Scan Failed", "Error Code: " + errorCode);
}
};
for connect device call gattCallback
private synchronized void connectToDevice(BluetoothDevice device, byte[] scanRecord) {
mGatt = device.connectGatt(getApplicationContext(), false, mBtGattCallback);
}
private BluetoothGattCallback mBtGattCallback = new BluetoothGattCallback() {
// override all methods
}

BLE RSSI SCAN APP ANDROID

I'm new on this and I don't know how I can print on the mobile phone the RSSI that I have scanned before. This is my code, tell me please what I'm making wrong.
I have to send this for a final project and I can't see the Rssi.
public class MainActivity extends AppCompatActivity {
//declare
private BluetoothAdapter mBluetoothAdapter;
private final static int REQUEST_ENABLE_BT = 1;
private BluetoothLeScanner mBluetoothLeScanner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
// Ensures Bluetooth is available on the device and it is enabled. If not,
// displays a dialog requesting user permission to enable Bluetooth.
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
//start and stop scan
mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
// Checks if Bluetooth LE Scanner is available.
if (mBluetoothLeScanner == null)
{
Toast.makeText(this, "Can Not Find BLE Scanner", Toast.LENGTH_SHORT).show();
finish();
return;
}
}
public class DeviceScanActivity extends ListActivity {
private BluetoothAdapter mBluetoothAdapter;
private boolean mScanning;
private android.os.Handler mHandler;
// Stops scanning after 10 seconds (10000).
private static final long SCAN_PERIOD = 1000;
private void scanLeDevice(final boolean enable) {
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable()
{
#Override
public void run()
{
mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
mScanning = false;
mBluetoothLeScanner.stopScan((ScanCallback) mLeScanCallback);
}
}, SCAN_PERIOD);
mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
mScanning = true;
mBluetoothLeScanner.startScan((ScanCallback) mLeScanCallback);
} else
{
mScanning = false;
mBluetoothLeScanner.stopScan((ScanCallback) mLeScanCallback);
}
}
}
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
#Override
public void run()
{
TextView SwitchOff = (TextView) findViewById(R.id.txonoff);
SwitchOff = (TextView) findViewById(R.id.txonoff);
SwitchOff.getText();
SwitchOff.setText("Potència= " + rssi + "dBm\n");
}
});
}
};
};

Categories

Resources