问题
I have set up an environment where the app receives location updates, which is handle on the onLocationChanged
callback.
// Setup the client.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
// Register the location update.
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
// Interface callback. Called every 5 seconds.
@Override
public void onLocationChanged(Location location) {
// Save the location coordinates to a file.
}
So far so good. Then, for my purposes, I saw the need of triggering the onLocationChanged
callback even if the app is not running - that's where BroadcastReceivers and Services come in.
I want a BroadcastReceiver to start a Service, that would save the location coordinates updates do a file. So, in my mind, the architecture would go something like:
// Register the BroadcasReceiver to the activity.
registerReceiver(mBroadcastReceiver, new IntentFilter());
// The BroadcastReceiver
public static class MyBroadcastReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
MyActivity.myContext.startService(new Intent(context, MyService.class));
}
}
// The Service class.
public static class MyService extends Service {
private boolean isRunning = false;
@Override
public void onCreate() {
isRunning = true;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Creating new thread for my service.
//Always write your long running tasks in a separate thread, to avoid ANR
new Thread(new Runnable() {
@Override
public void run() {
// Save location updates.
}
//Stop service once it finishes its task
stopSelf();
}
}).start();
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onDestroy() {
isRunning = false;
}
}
All LocationServices API setup process (the first block of code below) is inside the activity onCreate
method.
So, how can I receive location updates from the tread's run()
method created by the Service, if the app is not running? The whole design is to be like that:
App not running/destroyed > A specific action trigger the Broadcasreceiver > The BroadcastReceiver trigger the Service > The Service trigger the location updates and save it to a file.
来源:https://stackoverflow.com/questions/31838342/android-saving-location-updates-using-locationservices-api-from-a-service