停止LocationListener服务时出现问题

时间:2011-08-23 20:51:57

标签: android location intentservice

我有一个实现LocationListener的IntentService。它在我的应用程序运行时运行,并在我的应用程序关闭时被销毁。在其onHandleIntent方法中,我获得了一个LocationManager并注册了服务表单位置更新。在其onDestroy方法中,我调用:

locationManager.removeUpdates(this);

但是,这有时会导致NullPointerException:

08-23 20:45:09.826: ERROR/AndroidRuntime(6541): FATAL EXCEPTION: main
08-23 20:45:09.826: ERROR/AndroidRuntime(6541): java.lang.RuntimeException: Unable to stop service uk.ac.ic.doc.vmw10.wherewolf.helpers.Locater@44f53fa8: java.lang.NullPointerException
08-23 20:45:09.826: ERROR/AndroidRuntime(6541):     at android.app.ActivityThread.handleStopService(ActivityThread.java:3090)
08-23 20:45:09.826: ERROR/AndroidRuntime(6541):     at android.app.ActivityThread.access$3700(ActivityThread.java:125)
08-23 20:45:09.826: ERROR/AndroidRuntime(6541):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2099)
08-23 20:45:09.826: ERROR/AndroidRuntime(6541):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-23 20:45:09.826: ERROR/AndroidRuntime(6541):     at android.os.Looper.loop(Looper.java:123)
08-23 20:45:09.826: ERROR/AndroidRuntime(6541):     at android.app.ActivityThread.main(ActivityThread.java:4627)
08-23 20:45:09.826: ERROR/AndroidRuntime(6541):     at java.lang.reflect.Method.invokeNative(Native Method)
08-23 20:45:09.826: ERROR/AndroidRuntime(6541):     at java.lang.reflect.Method.invoke(Method.java:521)
08-23 20:45:09.826: ERROR/AndroidRuntime(6541):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-23 20:45:09.826: ERROR/AndroidRuntime(6541):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-23 20:45:09.826: ERROR/AndroidRuntime(6541):     at dalvik.system.NativeStart.main(Native Method)
08-23 20:45:09.826: ERROR/AndroidRuntime(6541): Caused by: java.lang.NullPointerException
08-23 20:45:09.826: ERROR/AndroidRuntime(6541):     at uk.ac.ic.doc.vmw10.wherewolf.helpers.Locater.onDestroy(Locater.java:137)
08-23 20:45:09.826: ERROR/AndroidRuntime(6541):     at android.app.ActivityThread.handleStopService(ActivityThread.java:3076)
08-23 20:45:09.826: ERROR/AndroidRuntime(6541):     ... 10 more

如果删除该行,则NullPointerException消失,但是当我关闭应用程序时,LocationListener不会停止。我有什么想法可以解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

如何将它包装在空检查中?

if (locationManager != null)
    locationManager.removeUpdates(this);