子線程更新主線程的方法-轉

來源:互聯網
上載者:User

標籤:

Android的UI更新只能在UI線程中,即主線程。子線程中如果要進行UI更新,都是要通知主線程來進行。

幾種實現方式總結如下,歡迎補充。

1、runOnUiThread()

子線程中持有當前Activity引用(假如為Activity mActivity;),即可以調用mActivity的runOnUiThread(Runnable r)方法。

2、post()和postDelay()

子線程如果持有某個View的引用,要對該View進行更新,則可調用該View對象的post(Runnable r)或postDelay(Runnable r)方法

Handler對象也有post()方法。其實在Android的源碼中,這些post()方法都是藉助下面的第3種方法:Handler + Message來實現的。

3、Handler + Message或者Handler + Thread + Message

主線程建立時,預設情況下是有Looper的,可以處理訊息佇列。

在主線程建立一個Handler對象,複寫其handleMessage()方法,在該方法中實現UI更新。

樣本:

private static final int MSG_CODE = 1001;
private Handler mHandler = new Handler()
{
@Override
public void handleMessage(Message msg)

{

//接收並處理訊息

if(msg.what == MSG_CODE)
{
//UI更新
}
}
};

public void doSomething()
{
new Thread()
{
@Override
public void run()

{

//子線程發送資訊

Message msg = mHandler.obtainMessage(MSG_CODE);
msg.sendToTarget();
}
}.start();

}

4、Broadcast

子線程中發送廣播,主線程中接收廣播並更新UI

5、AsyncTask

AsyncTask可方便地實現新開一個線程,並將結果返回給UI線程,而不需要開發人員手動去新開一個線程,也無須開發人員使用Handler,非常方便。

應當注意的是AsyncTask是一個抽象類別,其三個泛型參數的意義如下:
AsyncTask<Param, Progress, Result>
Param:發送給新開的線程的參數類型
Progress:表徵任務處理進度的類型。
Result:線程任務處理完之後,返回給UI線程的值的類型。

該類中有四個抽象函數,onPreExecute(), doInBackground(Params... param),
onProgressUpdate(Progress... progress), onPostExecute(Result result)。
除了,doInBackground(Params...)方法,其它三個方法都運行在UI線程。

自訂一個類繼承AsyncTask並至少實現doInBackground()函數。在該函數中執行的過程中,可以隨時調用publishProgress(Progress...)報告其執行進度。此時會觸發另一個方法onProgressUpdate(Progress... progress),以便在UI線程中的某些控制項(如ProgressBar)上更新任務處理的進度。

也可以等doInBackground()執行完,進入onPostExecute()方法後,再進行UI控制項的更新。

可在任意時間,任意線程中,取消AsyncTask開啟的任務(調用自訂的AsynTask子類的cancel(boolean mayInterruptIfRunning)方法)

使用樣本如下:

//如果沒記錯的話,這個例子應該是之前總結的時候從官網剪下來的

public void onClick(View v) {
   new DownloadImageTask().execute("http://example.com/image.png");
}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
   /** The system calls this to perform work in a worker thread and
     * delivers it the parameters given to AsyncTask.execute() */
   protected Bitmap doInBackground(String... urls) {
       return loadImageFromNetwork(urls[0]);
   }
   
   /** The system calls this to perform work in the UI thread and delivers
     * the result from doInBackground() */
   protected void onPostExecute(Bitmap result) {
       mImageView.setImageBitmap(result);
   }
}

子線程更新主線程的方法-轉

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.