Android的UI thread并非线程安全,因此所有UI的操作必须在UI thread完成。
主要方法有:
1,使用AsyncTask,
AsyncTask中的onXxxxx callback都在UI thread中执行,
后台任务在doInBackground方法中执行完成后会把结果传递给onPostExecute,
可以在onPostExecute中更新UI
2,使用Handler
非UI thread可以向UI thread的Handler发message,Handler收到message后更新UI.
在work thread中使用如下方法可以拿到UI thread的handler
Handler n = new Handler(Looper.getMainLooper()){
public void handleMessage(Message m){ }
}
3,activity的runOnUiThread(Runnable r)方法
在非UI thread中
mActivity.runOnUiThread( new Runnable() {
public void run() {
//操纵UI
}
});
4,view的post和postDelay方法
在非UI thread中
mImageView.post( new Runnable(){
public void run() {
//操纵mImageView
}
});