gpt4 book ai didi

Android:如何获取指向服务的指针?

转载 作者:行者123 更新时间:2023-11-30 04:25:02 24 4
gpt4 key购买 nike

我有一个带有服务的应用程序。这个服务启动了worker Thread,这个线程需要一个指向Service实例的指针(它调用了这个服务的一些方法)。

现在我只需将 ServiceonCreate() 方法中的 this 指针传递给我自己的 Runnable 构造函数,但它可以正常工作,直到我关闭我的应用程序。当应用程序重新启动时,指针确实出现了问题。我仍然无法弄清楚哪里出了问题,但似乎指向我的服务实例的指针是指向奇怪的另一个服务实例的指针,指向我的 Runnable 的指针也是错误的。

如果我终止我的应用程序,那么下次它会正常工作,但在重新启动后会出现同样的问题。

我怀疑我无法从 Service 的 onCreate() 方法传递 this 指针,但是,我怎样才能从从 onCreate() 方法开始的线程?

更新:我刚刚发现我有完全相同的singleton issue . Runnable 是一个单例。但我仍然找不到任何好的解决方案,除了根本不在 Android 中使用单例。也许,有什么建议吗?

最佳答案

this thread needs a pointer to an instance of Service (it calls some methods of this service).

Java 中没有指针。 Java 等价物是“对象引用”。

until i close my app

Android 中没有“关闭”“应用程序”这样的概念。

I still can't figure out what especially is wrong, but it seems like pointer to my instance of Service is a pointer to strange another instance of Service, and pointer to my Runnable is wrong too.

这是非常可能的,如果您停止了原来的 Service 并泄漏了线程,然后再次启动 Service。您可能已经结束了两个线程,一个线程持有您的 Service 的已失效副本。

how can i get pointer to instance of my Service from the thread that starts from onCreate() method?

那不是你的问题。你的问题,不管是什么,都在别处。

关于Android:如何获取指向服务的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8660891/

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