在android平台下,進行多線程編程時,經常需要在主線程之外的一個單獨的線程中進行某些處理,然後更新使用者介面顯示。但是,在主線線程之外的線程中直接更新頁面顯示的問題是:系統會報這個異常,android.view.viewroot$calledfromwrongthreadexception: only the original thread that created a view hierarchy can touch its views. (只有原始建立這個視圖層次(view hierachy)的線程才能修改它的視圖(view)。)。
也就是說必須在程式的主線程(也就是ui線程)中進行更新介面顯示的工作。可以採用下面的方法之一來解決:
解決方案1:在activity.oncreate(bundle savedinstancestate)中建立一個handler類的執行個體, 在這個handler執行個體的handlemessage回呼函數中調用更新介面顯示的函數。例如:
public class ExampleActivity extends Activity {Handler h = null;@overridepublic void onCreate(Bundle savedinstancestate){h = new Handler(){@overridepublic void handleMessage(Message msg){// call update gui method.}};}}
在其它的函數中,利用 send族或post族函數向這個h發送或郵寄訊息即可。
解決方案2:利用activity.runonuithread(runnable)
把更新ui的代碼建立在runnable中,然後在需要更新ui時,把這個runnable對象傳給activity.runonuithread(runnable)。 這樣runnable對像就能在ui程式中被調用。