Stop Location Service

whenever I try to stop my location service on android I get a NullPointerException. anyone has some tips on how to do it? I want to implemented on some activities onstop() and ondestroy() methods. Here is my service code:


package com.storetab;

public class LocationService extends Service {
static LocationManager locationManager;
static Location lastknown;
final static String MY_ACTION = "MY_ACTION";
static LocationListener ll;
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;

public int onStartCommand(Intent intent, int flags, int startId){

 final Criteria criteria = new Criteria();
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.getBestProvider(criteria, true);
ll = new MyLocListener();

locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, ll);

lastknown = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Intent intent1 = new Intent();
intent.putExtra("location1", lastknown);


private class MyLocListener implements LocationListener {
public void onLocationChanged(Location location) {


public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
Log.d("1Provider DIsabled", "Provider Disabled");

public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Log.d("1Provider Enabled", "Provider Enabled");

public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
Log.d("1Provider Changed", "Service Status Changed");

@Override public void onDestroy() {

preguntado el 31 de julio de 12 a las 10:07

07-31 10:56:36.609: E/AndroidRuntime(11337): at$ 07-31 10:56:36.609: E/AndroidRuntime(11337): at 07-31 10:56:36.609: E/AndroidRuntime(11337): at dalvik.system.NativeStart.main(Native Method) 07-31 10:56:36.609: E/AndroidRuntime(11337): Caused by: java.lang.NullPointerException 07-31 10:56:36.609: E/AndroidRuntime(11337): at com.storetab.LocationService.onDestroy( -

Your locationManager in ondestroy is null. Put a null check before the call -

but why is it null? the service is only destroyed after it has been created, it makes no sense -

1 Respuestas

En su onStartCommand() tienes este código:

LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

Esto crea un variable local , que son locationManager, cual cueros the class variable you have declared above that at the top of the class:

static LocationManager locationManager;

Los programas variable de clase estática locationManager never gets set to anything, so it is null in onDestroy().

To fix that, just change it to this in onStartCommand():

locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

Respondido 01 ago 12, 17:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.