开发者

Activity with backgroundthread, not innerclass, communication

开发者 https://www.devze.com 2023-02-19 04:53 出处:网络
Hey all, this will contain a few questions since I don\'t seem to really get it. I have 1 class, the activity. which should display informations.

Hey all, this will contain a few questions since I don't seem to really get it.

I have 1 class, the activity. which should display informations.

Then I have a background thread, extends runnable, which keeps getting new data (there for I didn't use AsyncTask, I could use it as a service, but since I hold a some critical resources in it, I would like not have it released when exiting the activity thread)

But I am in great doubt how to communicate between these 2.

First I thought of Intent, but these seem to be used mostly for launching other activities, or alike, and I need something permanent, since data will be in 开发者_StackOverflow中文版a steady flow.

Then I found out handler, but this doesn't seem to work when my thread is not an innerclass, so I'm thinking about either going back to the old Java observer pattern, if it's not possible to somehow pass the handler to the outerclass.

Any thoughts would be greatly appreciated

Sincerely Anders Metnik


There is a mechanism for your case - it is called handlers. Read more here.

As for having thread as inner class: Create your thread as a separate class, add a constructor with a handler parameter and pass it from your activity.


Thread is not suppose to live outside Creator Activity Context, especially you want to preserve it out of Activity, better use Service (and manage the thread) to hold those data.

Intent is the best in terms of communicating between contexts. I think one of the scenario you can adopt is like this:

Application-class: holds those 'permanent' data you mentioned Service-class: Work (background) and send out "intents" to signal the update state of the operations Activity-class: Intent Receiver. Whenever intent signal received, grab the necessary data from the Application-class.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号