android - 为什么我的 LocationListener 变为空?

标签 android location locationmanager locationlistener

我在名为 myService 的服务中遇到有关 LocationListener 的问题。

这是我的代码:

///onStart method ..
onStart() {
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE)
    .
    .
    provider = locationManager.getBestProvider(criteria, true);
    locationListener = (LocationListener) new MyLocationListener();
    locationManager.requestLocationUpdates(provider, 0, 0, locationListener);
}

在我的 Activity 中有一个应该停止服务的按钮。单击我正在执行的按钮:

stopService(new Intent(getApplicationContext(), myService.class)

myService.java 文件中我有:

////onDestroy method....
onDestroy() {
    locationManager=(LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.removeUpdates(locationListener); //Getting **exception here ....
}

我得到以下异常:

java.lang.IllegalArgumentException: listener==null at android.location.LocationManager.removeUpdates(LocationManager.java:799) at 
<.package_name>myService.onDestroy(myService.java:407) 

不知道为什么listener无缘无故变成null。请你能告诉我我哪里出错了!

最佳答案

只有当内存不足时,Android 系统才会强制停止服务,并且它必须为具有用户焦点的 Activity 回收系统资源。如果服务绑定(bind)到一个以用户为中心的 Activity ,那么它就不太可能被杀死,如果服务被声明在前台运行(稍后讨论),那么它几乎永远不会被杀死。否则,如果该服务已启动并长时间运行,那么随着时间的推移,系统将降低其在后台任务列表中的位置,并且该服务将变得极易被杀死——如果您的服务已启动,那么您必须将其设计为优雅地处理系统重启。如果系统终止了您的服务,它会在资源再次可用时立即重新启动它(尽管这也取决于您从 onStartCommand() 返回的值,如后所述)。有关系统何时可能销毁服务的更多信息,请参阅进程和线程文档。

关于android - 为什么我的 LocationListener 变为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2153873/

相关文章:

Android:手机处于 sleep 状态时GPS位置更新?

iOS 8.1 CoreLocationManager requestWhenInUseAuthorization 不提示 AlertView

java - 将数组列表内容添加到给出空文本的 TextView

android - 在 Android 中检测当前音频路由的有效方法?

android - 如何使用 FFMpeg 从多个图像序列创建视频?

android - 如何在电子邮件中发送带有 html 表格输出的电子邮件

android - 是否可以使用 Google 的新融合位置提供程序来模拟位置?

iOS:XCUITest 中的模拟器位置不起作用

iphone - CLLocationManager 的 distanceFilter 属性无法正常工作

android - 为什么 location.getSpeed() 在 android 中使用 NETWORK_PROVIDER 时总是返回 0?