HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Android Studio Background Service to Update Location

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
updatebackgroundandroidservicestudiolocation

Problem

I have this background service, which runs continuously even when the application closed (Paused or Stopped).

The service is to retrieve the user location and post it to server.

```
public class LocationUpdaterService extends Service
{
public static final int TWO_MINUTES = 120000; // 120 seconds
public static Boolean isRunning = false;

public LocationManager mLocationManager;
public LocationUpdaterListener mLocationListener;
public Location previousBestLocation = null;

@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public void onCreate() {
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationListener = new LocationUpdaterListener();
super.onCreate();
}

Handler mHandler = new Handler();
Runnable mHandlerTask = new Runnable(){
@Override
public void run() {
if (!isRunning) {
startListening();
}
mHandler.postDelayed(mHandlerTask, TWO_MINUTES);
}
};

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mHandlerTask.run();
return START_STICKY;
}

@Override
public void onDestroy() {
stopListening();
mHandler.removeCallbacks(mHandlerTask);
super.onDestroy();
}

private void startListening() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (mLocationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER))
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mLocationListener);

if (mLocationManager.getAllProviders().contains(LocationMana

Solution

To save power you can use/implement a function to detect when the user is stationary. You can for example define a user in stationary state when the location has not changed in more than 2 minutes (set this parameter so it does not fire too often, as when the user stops at a red light). When stationary states are detected, stop listen for location updates from the GPS and start listen for SIGNIFICANT_MOTION_SENSOR to detect active states. Be aware that not all models have this software sensor so you have to support situations when this is the case.

Context

StackExchange Code Review Q#123933, answer score: 3

Revisions (0)

No revisions yet.