轉載請標明出處:https:////www.cnblogs.com/tangZH/p/6107556.html
更多精彩文章: http://77blogs.com/?p=138
利用Activity.runOnUiThread(Runnable)把更新ui的代碼創建在Runnable中,然后在需要更新ui時,把這個Runnable對象傳給Activity.runOnUiThread(Runnable).
Runnable對像就能在ui程序中被調用。
/** * Runs the specified action on the UI thread. If the current thread is the UI * thread, then the action is executed immediately. If the current thread is * not the UI thread, the action is posted to the event queue of the UI thread. * * @param action the action to run on the UI thread */ public final void runOnUiThread(Runnable action) { if (Thread.currentThread() != mUiThread) { mHandler.post(action); } else { action.run(); } }
從上面的源代碼中可以看出,程序首先會判斷當前線程是否是UI線程,如果是就直接運行,如果不是則post,這時其實質還是使用的Handler機制來處理線程與UI通訊。
private ProgressDialog progressDialog;
Context mContext;
progressDialog = new ProgressDialog(mContext); String stri = mContext.getResources().getString(R.string.Is_sending_a_request); progressDialog.setMessage(stri); progressDialog.setCanceledOnTouchOutside(false); progressDialog.show(); new Thread(new Runnable() { public void run() { try { ((Activity)mContext).runOnUiThread(new Runnable() { public void run() { progressDialog.dismiss(); String s1 = mContext.getResources().getString(R.string.send_successful); Toast.makeText(mContext, s1, Toast.LENGTH_LONG).show(); } }); } catch (final Exception e) { ((Activity)mContext).runOnUiThread(new Runnable() { public void run() { progressDialog.dismiss(); String s2 = mContext.getResources().getString(R.string.Request_add_buddy_failure); Toast.makeText(mContext, s2 + e.getMessage(), Toast.LENGTH_LONG).show(); } }); } } }).start();
用這種方式創建ProgressDialog就比較方便,或者刷新adapter也比使用Thread+Handler方便。
如果不是在activity中創建,需要在前面加上((Activity)mContext). 。