gpt4 book ai didi

android - 在 android 上,我将如何创建一个扩展 Location Listener 的类,以便我的主要 Activity 和 Intent Service 可以使用同一个对象?

转载 作者:行者123 更新时间:2023-11-29 22:11:09 24 4
gpt4 key购买 nike

所以我计划创建一个需要获取用户位置的应用程序,它将有一个名为 LocationController 的类,该类实现了 LocationListener 接口(interface)。

我想要实现的是,一旦主要 Activity (现在称为 MainActivity)开始(在其 onCreate 方法中)调用我的 LocationController 对象并让它开始获取位置修复和更新。

但是,我还需要实现一个 IntentService 或服务,即使在主要 Activity 关闭后仍会继续运行(即调用 onPause 和/或 onStop),这服务需要访问与主 Activity 在 onCreate 方法中启动的完全相同的 LocationController 对象,以获取一些位置读数。

现在,我花了一些时间研究如何将数据从 Activity 传递到服务,并研究了 SerializableBundleParcel 对象,它们都不能传递 LocationListenerLocation 对象,所以这对我来说不是一个很好的选择(除非我错过了什么,在这种情况下,我接受建议)。

我想到的另一个选择可能是使用静态对象。基本上,让 LocationController 成为一个静态类,这样 MainActivity 就可以调用它的方法来开始获取位置修复,而且即使在 MainActivity 之后它也继续存在 已终止。但是,我仍然对如何执行此操作感到模糊。例如,我是将整个 LocationController 设为静态对象还是将其某些方法设为静态?

谁能帮我解决这个问题?

更新:

所以我采纳了kabuko的建议,在主要 Activity 类上写了以下内容:

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 类中的位置 Controller (称之为 MyService),我将位置 Controller 作为主要 Activity 类的静态成员访问,例如所以:

public class MyService extends IntentService {
private LocationController locationController = null;

public MyService() {
super("MyService");
locationController = MainActivity.getLocationController();
...
}

....

} // end of class

最佳答案

您可以为您的 LocationController 类创建一个单例实例,这实际上是“让您的整个 LocationController 成为一个静态对象”。请记住,随着您的 Activity 停止,您的服务将维持您的应用程序的生命周期。如果您希望它长时间运行并处理多个“任务”,您可能需要小心 IntentService,它会在停止工作后关闭(可能会终止您的应用程序和您的单例)。

关于android - 在 android 上,我将如何创建一个扩展 Location Listener 的类,以便我的主要 Activity 和 Intent Service 可以使用同一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9607086/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com