Search code examples
androidservicegpslocationlistener

How to get location in Android within a service


I want to start a service which will run in the background, and will show latitude and longitude every 30 to 45 seconds. Below is my code which I'm using:

public class LocalService extends Service implements LocationListener {
    private final static String TAG = "LocalService";
    LocationManager lm;


    public LocalService() {
    }

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

    @Override
    public void onCreate() {
        subscribeToLocationUpdates();
    }

    public void onLocationChanged(Location loc) {
        Log.d(TAG, loc.toString());
        Toast.makeText(getApplicationContext(), loc.getLatitude() + " - " + loc.getLongitude(), Toast.LENGTH_LONG).show();
        Log.i("Location", loc.getLatitude() + " - " + loc.getLongitude());
    }

    public void onProviderEnabled(String s) {
    }

    public void onProviderDisabled(String s) {
    }

    public void onStatusChanged(String s, int i, Bundle b) {
    }

    public void subscribeToLocationUpdates() {
        this.lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        this.lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30, 0, this);
    }
}

I'm calling my service like this:

startService(new Intent(TimerServiceActivity.this,
         LocalService.class));

This is my manifest code for service:

<service android:name="LocalService" >

Whenever I am running this code it gives me an error message that unfortunately, TimerService has stopped.


Solution

  • Do you have the permissions added in your manifest?

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    

    I instead highly recommend using this library optimized for battery usage and is rather simple to use:

    http://code.google.com/p/little-fluffy-location-library/

    Based on the concepts in, and some code adapted from, android-protips-location by Reto Meier, from his blog post A Deep Dive Into Location.