所以我计划创建一个需要获取用户位置的应用程序,它会有一个LocationController
实现LocationListener
接口的类。
我想要实现的是,一旦主要活动(MainActivity
现在调用它)开始(在它的onCreate
方法中)调用我的LocationController
对象并让它开始获取位置修复和更新。
但是,我还需要实现一个 IntentService 或 Service ,即使在主要活动关闭后(即调用onPause
and or onStop
)也将继续运行,并且该服务需要访问与LocationController
主要活动在方法中启动的相同对象onCreate
以获得一些位置读数。
现在,我花了一些时间研究如何将数据从活动传递到服务并查看Serializable
,Bundle
和Parcel
对象,它们都不能传递LocationListener
或Location
对象,所以这对我来说不是一个选择(除非我错过了什么,在这种情况下,我愿意接受建议)。
我想到的另一个选择可能是静态对象。基本上,有LocationController
一个静态类,以便可以调用它的方法来开始获取位置修复,但即使在被终止MainActivity
后它也继续存在。MainActivity
但是,我仍然不清楚如何做到这一点。例如,我是让我的整个LocationController
对象成为静态对象,还是让其中的一些方法成为静态对象?
谁能帮我这个?
更新:
于是我采纳了歌舞伎的建议,在主活动课上写了以下内容:
public void setLocationController() {
if (locationController == null)
this.locationController = new LocationController(this);
}
和
public static LocationController getLocationController() {
// make sure to have called setLocationController() early in your
// activity's life. onCreate is a good place
return this.locationController;
}
,其中设置了一个单例,但要访问我的 IntentService 类中的位置控制器(调用它MyService
),我将位置控制器作为主活动类的静态成员访问,如下所示:
public class MyService extends IntentService {
private LocationController locationController = null;
public MyService() {
super("MyService");
locationController = MainActivity.getLocationController();
...
}
....
} // end of class