开发者

Design question regarding multiple GUI component refresh scenario

Here is my scenario: I have to write an android application which displays two tickers on one screen(e.g news ticker and stock ticker). Data for both the tickers come from separate URL's. I'm trying to come up with a efficient solution. So here is my approach so far

Create separate class to fetch data from URL's(news and ticker). These classes should be completely responsible for fetching the data from server as well as updating the data on the UI component which is defined in the Activity.

So i guess, each of the class should have 2 private inner class (threads) one to fetch data from server and another to update the GUI. Once the fetch thread gets all the data, the display thread will start to paint it on the GUI component.

My question is

  1. Is this a correct approach? I think this might work, but i'm trying to find if there is a better way to do things, like using AsyncTask etc. need some expert advise here.

  2. I do not want to pass the reference of GUI components(textView) from Activity to Thread class (trying to decouple), so I was thinking of passing instance of handler from

    Activity to these classes. That way the inner thread class can post a message in handler and then 开发者_Python百科in Activity i can get the message from handler to update the GUI component. Is it ok to pass the reference of handler to thread. Is this how it is supposed to be done?

I'm completely ok with changing the above approach if there is a better way, so please let me know how would you tackle this problem.

Thanks


So i guess, each of the class should have 2 private inner class (threads) one to fetch data from server and another to update the GUI. Once the fetch thread gets all the data, the display thread will start to paint it on the GUI component.

No. You cannot modify the GUI from a background thread. You need a background thread for downloading and parsing the data. You not only do not need a background thread for updating the GUI, but it won't do you any good.

I think this might work, but i'm trying to find if there is a better way to do things, like using AsyncTask etc. need some expert advise here.

AsyncTask is one possibility, and is probably an improvement over plain threads. Using an IntentService is another approach. The difficulty with threads or AsyncTasks in the activity is that dealing with configuration changes (rotation, dock/undock, etc.) gets annoying. Using an IntentService and a Messenger can streamline that. Here is a sample application demonstrating this technique.

Is it ok to pass the reference of handler to thread.

Yes.

Is this how it is supposed to be done?

So long as the handler is a data member of the activity (so it does not get garbage-collected, etc.), yes. AsyncTask hides that from you, so you do not need to worry about that problem.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜