简体   繁体   中英

Changing a TextView in another class from a Service

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM