Having read lots of snippets and tutorials, I’m still (or even more) confused about the road to take. I need a thread/backgroundtask, that listens for incoming events on a socket and report any incomings to the UIThread. What would be the preferred way to choose? Own thread or multitasking? Best way to transfer data to the main thread?
Thanx for any thoughts on the matter.
Regards,
Marcus
Considering your answers below, I’ve tried the following:
MainActivity:
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();
} }
An my runnable:
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);
}
} }
My layout only holds an additional checkbox:
<?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" />
Good thing is, the toast appears. Bad thing, the cehckbox is unresponsive and the app crashes pretty quick. Isn’t that, how it should be done?
Edit: the msg in sendMessage in the WorkerThread seems to be the troublemaker as the exception says, the message is all read in use?
Here’s the code, that’s finally working:
UIThread:
WorkerThread:
HTH someone. Thanx to all for the input.