I´m working on a android app of inside of a Contact tracing project. What i need right now is make a background process (idk if, service, foreground service, worker, etc), that can keep the BLE advertiser sending beacons even if the application closes. Is working without issues on the main thread but when i try to convert in a service, it can´t start. This is the service class that i tried:
public class AdvertiserService extends Service {
private BluetoothLeAdvertiser advertiser;
private AdvertiseSettings settings;
private AdvertiseCallback callback;
@Override
public void onCreate() {
super.onCreate();
advertiser = BluetoothAdapter.getDefaultAdapter().getBluetoothLeAdvertiser();
settings = new AdvertiseSettings.Builder()
.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
.setConnectable(false)
.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH)
.setTimeout(0)
.build();
callback = new AdvertiseCallback() {
@Override
public void onStartSuccess(AdvertiseSettings settingsInEffect) {
super.onStartSuccess(settingsInEffect);
}
@Override
public void onStartFailure(int errorCode) {
super.onStartFailure(errorCode);
}
};
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
long userId =
Long.parseLong(PreferenceManager.getDefaultSharedPreferences(this)
.getString(getString(R.string.user_id_pref_key), "0"));
MeetingBeacon beacon = new MeetingBeacon(userId, userId);
Log.d("MEETING_BACON", beacon.getBeaconUUID().toString() );
AdvertiseData data = new AdvertiseData.Builder()
.addServiceData(beacon.getBeaconUUID(), beacon.getBeaconData())
.build();
advertiser.startAdvertising(settings, data, callback);
return START_STICKY;
}
@Override
public void onDestroy(){
Log.d("ADVER-Sv","Automate service destroyed...");
advertiser.stopAdvertising(callback);
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public boolean stopService(Intent name) {
Log.d("SCAN-Sv","Automate service stop...");
advertiser.stopAdvertising(callback);
stopSelf();
return super.stopService(name);
}
}
And i´m starting this service from main thread as:
advertiserService = new Intent(this, AdvertiserService.class);
if(advertiserEnabled) {
ComponentName ret = startService(advertiserService);
if(ret != null){
Log.d("SERVICE:", sv.toString());
}
Log.d("SERVICE ", "fail");
}
But ret is always null , so the service cannot start. Idk if using service is the better solution in this case. Anyone can suggest which could be the better solution to solve this problem?