什麼是最好的方式來更新我的用戶界面?我應該去處理程序還是runOnUiThread?
如果您的Runnable
需要更新UI,請在runOnUiThread
上發佈。
但是並不總是可以在UI線程上發佈Runnable
。
想想您需要執行的場景網絡/ IO操作或調用Web服務。在這種情況下,您不能將Runnable
發佈到UI線程。它會拋出android.os.NetworkOnMainThreadException
這些類型的Runnable
應運行在不同的線程上,如HandlerThread。完成操作後,您可以使用已與UI線程關聯的Handler
將結果發回UI線程。
public void onClick(View view) {
// onClick on some UI control, perform Network or IO operation
/* Create HandlerThread to run Network or IO operations */
HandlerThread handlerThread = new HandlerThread("NetworkOperation");
handlerThread.start();
/* Create a Handler for HandlerThread to post Runnable object */
Handler requestHandler = new Handler(handlerThread.getLooper());
/* Create one Handler on UI Thread to process message posted by different thread */
final Handler responseHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
//txtView.setText((String) msg.obj);
Toast.makeText(MainActivity.this,
"Runnable on HandlerThread is completed and got result:"+(String)msg.obj,
Toast.LENGTH_LONG)
.show();
}
};
NetworkRunnable r1 = new NetworkRunnable("http://www.google.com/",responseHandler);
NetworkRunnable r2 = new NetworkRunnable("http://in.rediff.com/",responseHandler);
requestHandler.post(r1);
requestHandler.post(r2);
}
class NetworkRunnable implements Runnable{
String url;
Handler uiHandler;
public NetworkRunnable(String url,Handler uiHandler){
this.url = url;
this.uiHandler=uiHandler;
}
public void run(){
try {
Log.d("Runnable", "Before IO call");
URL page = new URL(url);
StringBuffer text = new StringBuffer();
HttpURLConnection conn = (HttpURLConnection) page.openConnection();
conn.connect();
InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());
BufferedReader buff = new BufferedReader(in);
String line;
while ((line = buff.readLine()) != null) {
text.append(line + "\n");
}
Log.d("Runnable", "After IO call:"+ text.toString());
Message msg = new Message();
msg.obj = text.toString();
/* Send result back to UI Thread Handler */
uiHandler.sendMessage(msg);
} catch (Exception err) {
err.printStackTrace();
}
}
}
'runOnUiThread'只是將'Runnable'發佈到'Handler'的快捷方式。 'Handler'是Android定義的每個(?)交叉線程通信工具的基礎(例如'AsyncTask'的'onPostExecute'使用'Handler'來傳遞'doInBackground'的結果)。 – zapl