从服务更改另一个类中的 TextView
我有两门课程,一门是标准活动,另一门是服务。我希望服务在服务中发生的某些事件上更新 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我强烈建议加强逻辑解耦。让
Service
告诉Activity
更新TextView
。您可以通过广播
Intent
来做到这一点,或者让Activity
提供Service
调用的侦听器对象。无论哪种情况,请确保 Activity 与服务分离(取消注册侦听器或广播Intent
接收器),以免导致内存泄漏。当然,这仅在活动实际运行时才有效。
I would strongly recommend greater logical decoupling. Have the
Service
tell theActivity
to update theTextView
.You can do that via a broadcast
Intent
, or by having theActivity
provide a listener object that theService
calls. In either case, be sure the Activity detaches from the service (unregisters the listener or broadcastIntent
receiver), lest you cause a memory leak.And, of course, this only works if the activity is actually running.