http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html
All components that run in the same process are instantiated in the UI thread
有兩個原則:
- Do not block the UI thread
- Do not access the Android UI toolkit from outside the UI thread
第1點透過thread可解決 , 第2點範例如下:
不安全:
public void onClick(View v) { new Thread(new Runnable() { public void run() { Bitmap b = loadImageFromNetwork("http://example.com/image.png"); mImageView.setImageBitmap(b); } }).start(); }
安全
public void onClick(View v) { new Thread(new Runnable() { public void run() { final Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png"); mImageView.post(new Runnable() { public void run() { mImageView.setImageBitmap(bitmap); } }); } }).start(); }
跨thread要存取UI Thread上的View , 可透過下列Function達成
若有多個Client端存取的Component , 如Bound Service或是Content Provider , 會需要Thread Safe的做法 , 避免多個操作均使用GUI Thread , 會透過Thread Pool方式 , 避開Main/GUI Thread
沒有留言:
張貼留言