Android 在其他線程中更新UI 線程

來源:互聯網
上載者:User

http://www.cnblogs.com/shangdahao/archive/2013/05/19/3069092.html

 

Android 在其他線程中更新UI 線程

方法一:Activity.runOnUiThread(Runnable )

(經驗之道: 這個最好用, 凡是要重新整理頁面的地方,

Activity.runOnUiThread( new Runnable()

   { public void run(){更新UI}}

);

方法二:子線程調用Handler的sendMessage(message)發送事件。

mHandler = new Handler() {     @Override     public void handleMessage(Message msg) {          //操作介面         myText.setText( 來自網路的資訊);        super.handleMessage(msg);     }    };  public class MyThread extends Thread {       public void run() {              // 耗時操作              loadNetWork();              Message msg = new Message();              mHandler.sendMessage(msg);//向Handler發送訊息,        }   }  

方法三:View.post(Runnable )

public void onClick( View v ) {          new Thread( new Runnable() {                  public void run() {                         // 耗時操作                            loadNetWork();                            myText.( new Runnable() {                                    myText.setText( 來自網路的資訊);                            });                   }          }).start();  }  

方法四:AsyncTask

//UI線程中執行  new DownloadImageTask().execute( "www.91dota.com" );  private class DownloadImageTask extends AsyncTask {      protected String doInBackground( String... url ) {           return loadDataFormNetwork( url[0] );//後台耗時操作      }        protected void onPostExecute( String result ) {            myText.setText( 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.