0

这是我第一次制作一个相当大的应用程序,其中有很多部分。

我想将 UI 和后台进程保留在不同的类中以避免混淆。但是,我如何以最好的方式在他们之间进行交流。到目前为止,我遇到了几种方法:

  1. 在不同的类中声明后台线程并在 UI 线程中定义其 onPostExecute() 方法。

        new SetupDefaultFeeds(context) {
        @Override
        protected void onPostExecute(List<Feed> result) {
            default_feeds = result;
    
            for (Feed t : result) {
                String log = t.toString();
                Log.d("DEFAULT feed", log);
            }
            menu_btn[0].performClick();
        }
    }.execute();
    
  2. 在后台和 UI 线程之间使用标志变量发出信号。

  3. 线程和处理程序。

还有其他方法吗?最好的方法是什么。谢谢 !

4

1 回答 1

1

Passing messages through a Handler is usually the most "Android-ish" way to do this. Trying to do all communication through flag variables is most likely going to be quite a headache.

Edit: Android itself doesn't provide a way for you to link the two classes together, you need to do that by hand. One way which works quite well is to create an interface for your communication and have either the UI class or background thread implement it. Then, when creating the class, you can pass a reference to the other object and communicate through the interface.

However, if you want to completely decouple the two classes, you might want to use a BroadcastReceiver instead and use it to send messages between the UI and background thread.

于 2012-10-15T08:29:12.143 回答