停止位置服务

时间:2012-07-31 09:35:24

标签: android android-service android-location

每当我尝试在android上停止我的位置服务时,我都会得到一个NullPointerException。谁有关于如何做的一些提示?我想在onstop()和ondestroy()方法上实现一些活动。这是我的服务代码:

LocationService.Java

package com.storetab;

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

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

 final Criteria criteria = new Criteria();
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setSpeedRequired(false);
criteria.setCostAllowed(true);
locationManager.getBestProvider(criteria, true);
ll = new MyLocListener();


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

lastknown = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Log.d("Teste","lastknown");
Intent intent1 = new Intent();
intent.putExtra("location1", lastknown);
intent.setAction(MY_ACTION);
sendBroadcast(intent1);   
Log.d("broadcastlast","lastknown");
return START_STICKY;

}

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() {
locationManager.removeUpdates(ll);
};
}

1 个答案:

答案 0 :(得分:0)

在您的onStartCommand()中,您有此代码:

LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

这会创建一个名为locationManager局部变量隐藏您在类顶部声明的类变量:

static LocationManager locationManager;

静态类变量 locationManager永远不会设置为任何内容,因此在null中为onDestroy()

要解决此问题,只需将其更改为onStartCommand()

locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);