Bookmark and Share

When you are running some heavy computation, sometimes the Android UI will hung until the computation is done, it is because main UI and computation are sharing the same thread.

Unlike Actionscript, Java is multi-threads language, you can create background thread to run heavy computation then pass message to handler:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.xllusion.threads;
 
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
 
// Need to implement Runnable
public class Threads extends Activity implements Runnable {
 
	private Thread _thread;
 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// Start new background thread
		_thread= new Thread(this);
		_thread.start();
	}
 
	public void run() {
		// Do computation here
		doSomeHeavyComputation();
		// Send message to handler
		_handler.sendEmptyMessage(0);
	}
 
	// This Handler is bound to the main thread
	private Handler _handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// Pass something to UI
		}
	};
}

It might seems a bit confused at first but you will get used to do this in Java.