从服务更改另一个类中的 TextView

发布于 2024-08-16 23:09:44 字数 504 浏览 4 评论 0原文

我有两门课程,一门是标准活动,另一门是服务。我希望服务在服务中发生的某些事件上更新 Activity 的 TextView (通过 .setText())。

我尝试通过在 Activity-Class 中编写类似于 setter 方法的方法来实现此目的,但是 TextView 不接受 static-引用,当我尝试调用 Activity- 的实例时,类(通过 MyActivityClassName aVariable = new MyActivityClassName();),我得到一个 NullPointer 异常,即使问题中的视图在调用时可见。

谁能告诉我我做错了什么:-)?这可能更像是一个基本的 Java 问题,而不是 Android 问题,但由于它可能与 Android 服务的性质有关,因此我仍然添加了 android 标签。

感谢您的帮助!

I have two classes, one is a standard activity, the other a service. I would like the service to update a TextView (via .setText()) of the Activity on certain events that happen within the service.

I've tried to achieve this by programming something like a setter-method inside the Activity-Class, but TextViews don't accept a static-reference, and when I try invoking an instance of the Activity-class instead (via MyActivityClassName aVariable = new MyActivityClassName();), I get a NullPointer Exception, even though the View in questions is visible at the time of the call.

Could anyone tell me what I'm doing wrong :-)? It is probably more of a basic Java question than an Android-one, but since it might have to do with the nature of Android-services, I've still added the android-tag.

Thanks for your help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

︶葆Ⅱㄣ 2024-08-23 23:09:44

我希望服务更新
TextView(通过.setText)的
发生的某些事件的活动
在服务内。

我强烈建议加强逻辑解耦。让 Service 告诉 Activity 更新 TextView

您可以通过广播Intent来做到这一点,或者让 Activity 提供 Service 调用的侦听器对象。无论哪种情况,请确保 Activity 与服务分离(取消注册侦听器或广播 Intent 接收器),以免导致内存泄漏。

当然,这仅在活动实际运行时才有效。

I would like the service to update a
TextView (via .setText) of the
Activity on certain events that happen
within the service.

I would strongly recommend greater logical decoupling. Have the Service tell the Activity to update the TextView.

You can do that via a broadcast Intent, or by having the Activity provide a listener object that the Service calls. In either case, be sure the Activity detaches from the service (unregisters the listener or broadcast Intent receiver), lest you cause a memory leak.

And, of course, this only works if the activity is actually running.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文