android 非同步載入

來源:互聯網
上載者:User

最近接觸到一些資料量大的處理頁面,那麼不可避免的就要用到非同步載入的方法。

總結了下:

1、最主流的是Handle + Thread方式;

2、使用AsyncTask

3、Activity.runOnUiThread(Runnable)
      View.post(Runnable)
      View.postDelayed(Runnable, long)

4、使用AsyncQueryHandler

分別給出樣本:

①Handle + Thread方式

    private Handler mHandler = new Handler();    public class MyThread extends Thread {         Message msg = new Message();            mHandler.sendMessage(msg);   }

②AsyncTask

   就是如果oncreate的時候 資料量就很大 而你恰恰也沒有想要分頁的打算 可以用這個了

    new LoadData().execute();    private class LoadData extends AsyncTask<Object, Object, Object>{        protected Object doInBackground(Object... params){    return null;  //查詢資料         }        protected void onPostExecute( String result ) {               myText.setText( result );  //重新整理頁面             }      }

③View.post(Runnable)

    比如向撥號盤搜尋連絡人的功能,就可以在監聽EditText變化的時候用到。

     private Handler searchListHandler = new Handler();    public void afterTextChanged(Editable s){        searchListHandler.post(runnable);    }    private Runnable runnable = new Runnable(){        public void run(){}    };

  Activity.runOnUiThread(Runnable)和View.post(Runnable)是類似的

    public void onClick( View v ) {        new Thread( new Runnable() {           public void run() {              loadNetWork();              Activity.runOnUiThread(new Runnable() {                  myText.setText("Farmer is a good man!");              });           }        }).start();    }

  View.postDelayed(Runnable, long) 傳遞給postDelayed方法中的Runnable對象在指定的時間後執行,並且是在此

   Handler所關聯的線程中執行。

    public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.main);         mHander.postDelayed(new MyThread(), 1000);     } 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.