0

Androidで位置情報サービスを停止しようとすると、NullPointerExceptionが発生します。誰かがそれを行う方法についていくつかのヒントを持っていますか? いくつかのアクティビティ onstop() および ondestroy() メソッドに実装したいと考えています。ここに私のサービスコードがあります:

LocationService.Java

パッケージ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);
};
}
4

1 に答える 1

0

あなたonStartCommand()はこのコードを持っています:

LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

これにより、 というローカル変数が作成されます。これにより、クラスの先頭で宣言したクラス変数がlocationManager表示になります。

static LocationManager locationManager;

静的クラス変数locationManager何にも設定されないためnullonDestroy().

これを修正するには、次のように変更しonStartCommand()ます。

locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
于 2012-08-01T16:16:22.437 に答える