2013-07-26 115 views
0

我想要做的是一個服務,我可以開始。當我開始服務時,它應該聽取GPS位置更新。所以我採取了以下服務:locationManager.requestLocationUpdates()導致NullpointerException

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。我上線以下NullPointerExpection用下面的代碼locationManager.requestLocationUpdates(minimumWaitBetweenLocationUpdatesInMilliSeconds, minimumLoctaionChangeInMeters, criteria, locationReceiverPendingIntent);

VM不提供監控信息
線程[< 1>主](暫停(例外的RuntimeException))
ActivityThread.handleCreateService(ActivityThread $ CreateServiceData) 線:2539 ActivityThread.access $ 1600(ActivityThread, ActivityThread $ CreateServiceData)線:141
ActivityThread $ H.handleMessage(消息)線:1316
ActivityThread $ H(處理程序).dispatchMessage(消息)線:方法.invokeNative(Object,Object [],Class,Class [],Class,int, boolean)行:不可用[native method] Method.invoke(Object, Object ...)line:511 ZygoteInit $ MethodAndArgsCaller.run()line:793
ZygoteInit.main(String [])line:560 NativeStart.main(String []) line:not available [native method]

這是什麼原因造成的?

回答

2

需要初始化的LocationManager

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

感謝這個提示。不知道我是如何設法監督的:D –

相關問題