So, I'm following this tutorial to implement a Service in my app. I implemented the Service succesfully. The service is activated and the notification is shown normally. Everything is fine except that I was not able to do work on the background thread. Please see below.
My goal is to set a mock location.
This is my onStartCommand for my Service:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
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("hi")
.setSmallIcon(R.drawable.icon)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
//do work on a background thread
new Thread(new Runnable() {
@Override
public void run() {
startMockLocation(); // doesn't actually mock device's location!
}
}).start();
return START_NOT_STICKY;
}
However, when I do this, it works fine but it's not efficient:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
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("hi")
.setSmallIcon(R.drawable.icon)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
// works great
timer.schedule(new TimerTask() {
@Override
public void run() {
startMockLocation();
//other stuff
}
}, 0, 1000);
return START_NOT_STICKY;
}
Mock location method:
public void startMockLocation(){ // this code is fine, nothing to fix here, something is wrong with the thread though :(
FusedLocationProviderClient locationProvider = new FusedLocationProviderClient(getApplicationContext());
locationProvider.setMockMode(true);
Location loc = new Location("gps");
Location mockLocation = new Location("gps"); // a string
mockLocation.setLatitude(48.8566);
mockLocation.setLongitude(2.3522);
mockLocation.setAltitude(loc.getAltitude());
mockLocation.setTime(System.currentTimeMillis());
mockLocation.setAccuracy(1f);
mockLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mockLocation.setBearingAccuracyDegrees(0.1f);
mockLocation.setVerticalAccuracyMeters(0.1f);
mockLocation.setSpeedAccuracyMetersPerSecond(0.01f);
}
locationProvider.setMockLocation(mockLocation);
}