manduinca
manduinca

Reputation: 147

RequestLocationUpdates Time of life

RequestLocationUpdates is a method of LocationManager, receives GPS information periodically.

I think if I send from onCreate application should not be a problem because it will not overcharge the main thread, I'm right?

If I want to receive information requestLocationUpdates, even after the application closed, from where should I send it?

Upvotes: 1

Views: 590

Answers (2)

manduinca
manduinca

Reputation: 147

In the end the best solution I found was to use Service, as follows:

public class GpsService extends Service implements LocationListener{

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    LocationManager LocManager =(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    LocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, this);
    return Service.START_STICKY;
}

public void onLocationChanged(Location location) {
    Log.i("location", String.valueOf(location.getLongitude()));
    Log.i("location", String.valueOf(location.getLatitude()));
}

public void onProviderDisabled(String provider) {
    Log.i("info", "Provider OFF");
}

public void onProviderEnabled(String provider) {
    Log.i("info", "Provider ON");
}

public void onStatusChanged(String provider, int status, Bundle extras) {
    Log.i("LocAndroid", "Provider Status: " + status);
    Log.i("info", "Provider Status: " + status);
}

}

And in onCreate () I launch the service:

public class PacienteApp extends Application {
@Override
public void onCreate() {
    Intent intent = new Intent(this, GpsService.class);
    this.startService(intent);
}
}

Using Broadcast Receiver is a good idea, but laborious as they are not allowed to use handlers within this class. And anyway you need the service to run in the background.

Upvotes: 0

Matt
Matt

Reputation: 5704

I think for the most part you will want to register a BroadcastReceiver. one of the broadcasts that you can watch for is when the location changes. There are a few logistical concerns with this such as how to interact with the BroadcastReceiver and how much battery your application will consume. A good summary of how to address these concerns can be found here.

Essentially you will want to make an Intent (your specific way of identfying an event you're looking for has happened) and a PendingIntent(A way to make that event interact with LocationServices).

PendingIntent launchIntent = PendingIntent.getBroadcast(context, 0, myIntent, 0);
manager.requestLocationUpdates(provider, minTime, minDistance, launchIntent);

Upvotes: 1

Related Questions