2013-05-13 41 views
1

我真的被困在这里,我已经阅读了很多有关android的线程,但我无法找到适合我的项目的答案。线程和事件

我有一个前端(管理GUI)和一个后端(管理数据和东西)。我需要在后台完成运行线程后立即更新GUI,但我无法弄清楚如何!

Main.java包前端

public class Main extends Activity { 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    Thread thread = new Thread() { 
     @Override 
     public void run() { 
      Server server = new Server(getApplicationContext()); 
     } 

    }; 
    thread.start(); 

Server.java封装后端

public static List<String> lista = new ArrayList<String>(); 
public Server(Context context) { 
    Revisar archivo = New Revisar(); 
    archivo.DoSomething(); 
} 

archivo.doSomething后完成我需要更新保存在静态列表中的后端数据的GUI。

有什么建议吗?

回答

0

正如你猜测的那样,你不能从后台线程更新GUI。

通常,要做你想做的事情,你使用消息处理机制将消息传递给GUI线程。通常情况下,您会传递一个Runnable,它将在GUI线程中执行。如果您已将Handler分类并添加了处理消息的代码,则还可以传递Message

消息传递给处理程序。您可以在GUI线程中创建自己的Handler,也可以使用其中一个已存在的Handler。例如,每个View对象都包含一个Handler。

或者您可以简单地使用runOnUiThread()活动方法。

模式1,处理器加上可运行:

// Main thread 
private Handler handler = new Handler(); 

    ... 

// Some other thread 
handler.post(new Runnable() { 
    public void run() { 
    Log.d(TAG, "this is being run in the main thread"); 
    } 
}); 

模式2,处理机加上消息:

// Main thread 
private Handler handler = new Handler() { 
    public void handleMessage(Message msg) { 
    Log.d(TAG, "dealing with message: " + msg.what); 
    } 
}; 

    ... 

// Some other thread 
Message msg = handler.obtainMessage(what); 
handler.sendMessage(msg); 

模式3,调用runOnUiThread():

// Some other thread 
runOnUiThread(new Runnable() {  // Only available in Activity 
    public void run() { 
    // perform action in ui thread 
    } 
}); 

模式4,将Runnable传递给视图的内置处理程序:

// Some other thread 
myView.post(new Runnable() { 
    public void run() { 
    // perform action in ui thread, presumably involving this view 
    } 
}); 
+0

在你提到的所有模式中,所有线程都在主活动中运行。我的问题是线程正在另一个类上运行,并在另一个包中运行 – 2013-05-14 00:11:22

+0

您是指整个单独的应用程序?还是服务? – 2013-05-14 00:25:31

+0

几乎整个单独的应用程序。我使用后端来处理数据,因为我被教导应该总是尝试使用MVC。所以后端是一个包含两个类的包,可以帮助我处理数据。 – 2013-05-14 00:27:30