I am using the Android BLE library to detect BLE tags. The callback is successful and return the BLE device name and RSSI value. The scan also continues indefinitely as long as the app is running on the UI thread.
However, when I close the application the scans stop, which is expected. I would like to however keep scanning in the background. I have read to use a foreground service. I have implemented the following code:
This is my Service, I tried putting the runnable in the start command as well. However, the callback still terminates after 15 to 30 seconds by itself. Why does the callback just terminate only when running it as a foreground service?
BluetoothManager btManager;
BluetoothAdapter btAdapter;
BluetoothLeScanner btScanner;
private NotificationManagerCompat notificationManager;
private static final String T
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate");
btManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
btAdapter = btManager.getAdapter();
btScanner = btAdapter.getBluetoothLeScanner();
//do heavy work on a background thread
new Thread (new Runnable() {
@Override
public void run() {
Log.d(TAG, "onCreate RUN");
btScanner.startScan(leScanCallback);
}
}).start();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand");
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Example Service")
.setContentText("input")
.setSmallIcon(R.drawable.ic_one)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
return START_STICKY;
}
private ScanCallback leScanCallback = new ScanCallback() {
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onScanResult(int callbackType, ScanResult result) {
Log.d(TAG, "BLE executed");
if(result.getDevice().getAddress().equals("EE:7E:DE:9B:65:46") && result.getRssi() > -80){
Log.d(TAG, "Tag found");
}
}
};
@Override
public void onDestroy() {
Log.d(TAG, "Destroy");
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}