阅读了很多片段和教程后,我仍然(甚至更多)对要走的路感到困惑。我需要一个线程/后台任务,它侦听套接字上的传入事件并将任何传入事件报告给 UIThread。什么是首选的选择方式?自己的线程还是多任务处理?将数据传输到主线程的最佳方式?
感谢您对此事的任何想法。
问候, 马库斯
考虑到您在下面的答案,我尝试了以下方法:
主要活动:
public class MainActivity extends Activity {
Handler handler = new Handler() {
    @Override
       public void handleMessage(Message msg) {
            toastSomething();
      };
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    threadstarter();
}
protected void threadstarter() {
    super.onStart();
    Thread backgroundthread = new Thread(new WorkerThread(handler));
    backgroundthread.start();
}
public void toastSomething() {
    Toast.makeText(this, "hello", Toast.LENGTH_SHORT).show();
} }
我的可运行文件:
public class WorkerThread implements Runnable {
Handler messageHandler;
WorkerThread(Handler incomingHandler) {
    messageHandler = incomingHandler;
}
public void run() {
    while (true) {
        for (int i = 0; i <= 100000; i++) {
            // wait a moment
        }
        messageHandler.sendEmptyMessage(1);
    }
} }
我的布局只包含一个额外的复选框:
<?xml version="1.0" encoding="utf-8"?>
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello" />
<CheckBox
    android:id="@+id/checkBox1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="CheckBox" />
好消息是,吐司出现了。糟糕的是,cehckbox 没有响应,应用程序崩溃得很快。是不是,应该怎么做?
编辑: WorkerThread 中的 sendMessage 中的消息似乎是麻烦制造者,因为异常说,消息都在使用中读取?