简体   繁体   中英

Android - Log fused location updates to a file in a background service

I'm attempting to Log Fused Location updates to a File from an unbound Service running in it's own process ':locationProcess'.

AndroidManifest.xm l

<service
   android:name=".LocationUpdate"
   android:process=":locationProcess"
   android:enabled="true"
   android:exported="true" />

LocationUpdate.java

public class LocationUpdate extends Service implements GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener {...

onBind is set to return null

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

and onStartCommand returns START_STICKY.

I'm creating the file in the Google play services onConnected callback method in the LocationUpdate service...

@Override
public void onConnected(Bundle arg0) {

    try {
        pwFile = new PrintStream(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "gps.csv"));
        pwFile.println("date,latitude,longtitude,altitude,bearing,accuracy");
    } catch (IOException e) {
        // TODO: Handle the exception
    }

    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    mLocationRequest.setInterval(10000);
    mLocationRequest.setFastestInterval(5000);
    startLocationUpates();
}

and writing it out the GPS details in the onLocationChange callback from the LocationListener ...

@Override
public void onLocationChanged(Location location) {
    currentLat = location.getLatitude();
    currentLng = location.getLongitude();

    // Get current date time
    Date newDate = new Date(System.currentTimeMillis());

    // Write lat and long out to a file
    pwFile.println(newDate.toString() + "," + String.format("%.6f", currentLat) + "," +
            String.format("%.6f", currentLng) + "," + String.format("%.4f", location.getAltitude()) + "," +
            String.format("%.4f", location.getBearing()) + "," + String.format("%.4f", location.getAccuracy()));
}

I am starting the service on the onCreate override of my Application class...

public class App extends Application {
   Intent LocationService;

   @Override
   public void onCreate() {
       super.onCreate();

       LocationService = new Intent(this, LocationUpdate.class);
       startService(LocationService);
   }
}

Which all works, App being declared in the <application> tag android:name="mypackage.app" of the Manifest.xml.

This is the part that doesn't...

I would like the Service to continue to log the positions to the file even when there is another application in the foreground.

It should stop logging if the user deliberately closes the application. Having read the Android documentation I thought my code would work correctly.

As far as I can tell, the Service does continue running when App is not in the foreground. It continues to run if the User specifically closes the App which I don't want and for some reason I don't understand the Service itself is being destroyed and recreated whilst the App is running so onConnected in the Service is being invoked again so the logging file is effectively being overwritten.

It is more of an architecture question I guess.

Basically, I want my location service to log reliably to a file whilst the App is not in the foreground after being started and to stop when the App is terminated by the User.

Hope makes sense. I've looked at lots of samples on Github but they only seem to log when the App is in the foreground.

Any help really appreciated, it's all driving me a bit crazy.

Thanks.

You made your service as a Start service (not an Intent Service). Then on the onStartCommand of service, returned START_STICKY . This will tell the OS, if for any reason you need to close the service, run it again when you have enough resources. In your case, when the user close the activity/kill the application the service process will be killed anyway, however it will normally be reopen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM