Reputation: 439
My app, requirement is to launch my service in background, when certain even take place, such as dialling a specific phone no. After that event, I need to get the user location and send it to a network.
This is what I have done so far, Broadcast Receiver to handle the even, and then after that I am launching my service. I am using the service to get the user current location, to achieve this I am running my service in background, for this looper and message concept, by overriding handleMessage, and passing intent information through onStartCommand overriding. Here is the code
@Override
public boolean handleMessage(Message message) {
Intent intent = (Intent) message.obj;
String action = intent.getAction();
if (START_EMERGENCY_SERVICE_ACTION.equalsIgnoreCase(action)) {
startMonitoring();
} else if (STOP_EMERGENCY_SERVICE_ACTION.equalsIgnoreCase(action)){
stopMonitoring();
stopSelf();
}
return true;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mHandler.sendMessage(mHandler.obtainMessage(0, intent));
return START_STICKY;
}
private void startMonitoring() {
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mLocationListener, mHandlerThread.getLooper());
}
And in my location listener class, I am getting the current location properly on its location update method.
@Override
public void onLocationChanged(Location location) {
Location bestLocation = getBestLocation(location);
if (bestLocation != lastLocation) {
Log.i(getClass().getSimpleName(),
String.format("Location Changed %s @ %d %f:%f (%f meters)",
bestLocation.getProvider(),
bestLocation.getTime(),
bestLocation.getLatitude(),
bestLocation.getLongitude(),
bestLocation.getAccuracy()));
}
}
Now, my challenge is to send this location to my web server, which has a rest API. Previously I have used httpUtil with AsyncTask in an activity, but how to do the same inside the background activity. Shall I launch another background service which will do the server communication. I am open for other architecture changes too.
I do have to support from 2.3 onwards, and right now I am using older way of location, but in future it should be scalable enough to migrate to fused location too.
Upvotes: 0
Views: 1038
Reputation: 4185
As your service is already running on a background thread, there are no issues to implement the web service code directly into the service. If you don't want the web service calls to block the thread you can also use another thread/AsyncTask/etc from your service.
Upvotes: 1