標籤:
第一種:
new Handler(context.getMainLooper()).post(new Runnable() {@Overridepublic void run() {// 在這裡運行你要想的操作 比方直接在這裡更新ui或者調用回調在 在回調中更新ui}});
context是你傳過來的context對象
另外一種:
// 假設當前線程是UI線程,那麼行動是馬上運行。假設當前線程不是UI線程,操作是公布到事件隊列的UI線程// 由於runOnUiThread是Activity中的方法,Context是它的父類,所以要轉換成Activity對象才幹使用((Activity) context).runOnUiThread(new Runnable() {@Overridepublic void run() {// 在這裡運行你要想的操作 比方直接在這裡更新ui或者調用回調在 在回調中更新ui}});第三種:
第三種是使用Handler的方法,往Handler中發送一個訊息,然後當Handler接收到你發送過來的訊息,再在Handler運行對應的操作
這是接收訊息啟動並執行代碼:
private Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);switch (msg.what) {case 1:button1.setText("點擊安裝");down = 1;break;case 2:down = 2;button1.setText("開啟");break;}}};
這是發送訊息的代碼:
// 往handler發送一條訊息 更改button的text屬性Message message = handler.obtainMessage();message.what = 1;handler.sendMessage(message);
Android 在子線程中更新UI的幾種方法