0

我想做的是我可以启动的服务。当我启动服务时,它应该监听 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 是一个广播接收器。我使用以下代码在行上得到以下 NullPointerExpection locationManager.requestLocationUpdates(minimumWaitBetweenLocationUpdatesInMilliSeconds, minimumLoctaionChangeInMeters, criteria, locationReceiverPendingIntent);

VM 不提供监控信息
Thread [<1> main] (Suspended (exception RuntimeException))
ActivityThread.handleCreateService(ActivityThread$CreateServiceData) line: 2539 ActivityThread.access$1600(ActivityThread, ActivityThread$CreateServiceData) line: 141
ActivityThread$H.handleMessage (Message) line: 1316
ActivityThread$H(Handler).dispatchMessage(Message) line: 99 Looper.loop() line: 137 ActivityThread.main(String[]) line: 5041
Method.invokeNative(Object, Object[], Class , Class[], Class, int, boolean) line: not available [native method] Method.invoke(Object, Object...) line: 511 ZygoteInit$MethodAndArgsCaller.run() line: 793
ZygoteInit.main(String[]) 行:560 NativeStart.main(String[]) 行:不可用 [本机方法]

这可能是什么原因?

4

1 回答 1

2

您需要初始化 locationManager

locationManager = getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(minimumWaitBetweenLocationUpdatesInMilliSeconds, minimumLoctaionChangeInMeters, criteria, locationReceiverPendingIntent);
于 2013-07-26T19:17:46.960 回答