3

LocationListener在我的服务中遇到了一个名为myService.

这是我的代码:

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

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

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。请你能告诉我哪里出错了!

4

2 回答 2

1

Android 系统仅在内存不足时才会强制停止服务,并且必须为具有用户焦点的活动恢复系统资源。如果服务绑定到具有用户焦点的活动,则它不太可能被杀死,如果服务被声明在前台运行(稍后讨论),那么它几乎永远不会被杀死。否则,如果服务已启动并且长时间运行,那么系统将随着时间的推移降低其在后台任务列表中的位置,并且该服务将变得非常容易被杀死 - 如果您的服务已启动,那么您必须将其设计为优雅地处理系统重新启动。如果系统终止了您的服务,它会在资源再次可用时立即重新启动它(尽管这也取决于您从 onStartCommand() 返回的值,稍后将讨论)。

于 2012-12-18T22:17:10.987 回答
0

我可以离开这里,但似乎您的服务被杀死然后(稍后)重新启动。为什么不将实例化的东西移到onCreate()?

于 2010-01-28T17:55:06.570 回答