locationManager.requestLocationUpdates()导致NullpointerException

时间:2013-07-26 19:09:11

标签: android android-intent

我想要做的是我可以开始的服务。当我启动服务时,它应该监听gps位置更新。所以我实施了以下服务:

public class TrackingService extends Service {

    protected LocationManager locationManager;
    protected PendingIntent locationReceiverPendingIntent;
    protected Intent locationIntent;

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

    @Override
    public void onCreate() {
        super.onCreate();

        locationIntent = new Intent(this, LocationReceiver.class);
        locationReceiverPendingIntent = PendingIntent.getBroadcast(this, 0, locationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE); // FINE tries to use GPS

        long minimumWaitBetweenLocationUpdatesInMilliSeconds = 15000;
        float minimumLoctaionChangeInMeters = 50;
        locationManager.requestLocationUpdates(minimumWaitBetweenLocationUpdatesInMilliSeconds, minimumLoctaionChangeInMeters, criteria, locationReceiverPendingIntent);    
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        locationManager.removeUpdates(locationReceiverPendingIntent);
    }
}

我在我的开始活动中启动此服务:

@Override
protected void onResume() {
    super.onResume();
    Intent serviceIntent = new Intent(this, TrackingService.class);     
    this.startService(serviceIntent);
}

LocationReceiver是一个BroadcastReceiver。我在行上使用以下代码locationManager.requestLocationUpdates(minimumWaitBetweenLocationUpdatesInMilliSeconds, minimumLoctaionChangeInMeters, criteria, locationReceiverPendingIntent);得到以下NullPointerExpection:

  

VM不提供监视器信息
  线程[< 1> main](Suspended(例外RuntimeException))
    ActivityThread.handleCreateService(ActivityThread $ CreateServiceData)   行:2539 ActivityThread.access $ 1600(ActivityThread,   ActivityThread $ CreateServiceData)line:141
    ActivityThread $ H.handleMessage(消息)行:1316
    ActivityThread $ H(Handler).dispatchMessage(Message)行:99     Looper.loop()行:137 ActivityThread.main(String [])行:5041
    Method.invokeNative(Object,Object [],Class,Class [],Class,int,   boolean)line:not available [native method] Method.invoke(Object,   对象...)行:511 ZygoteInit $ MethodAndArgsCaller.run()行:793
    ZygoteInit.main(String [])行:560 NativeStart.main(String [])   line:not available [native method]

原因可能是什么?

1 个答案:

答案 0 :(得分:2)

您需要初始化locationManager

locationManager = getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(minimumWaitBetweenLocationUpdatesInMilliSeconds, minimumLoctaionChangeInMeters, criteria, locationReceiverPendingIntent);