我有一个实现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不会停止。有什么想法我可以解决这个问题吗?

最佳答案

如何将其包装在null检查中?

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

关于android - 停止LocationListener服务时出现问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7167378/

10-12 05:13