android 异步执行方法

1.Handle

//①定义一个Handle
private Handler handler =new Handler(){
   @Override
   //当有消息发送出来的时候就执行Handler的这个方法
   public void handleMessage(Message msg){
      super.handleMessage(msg);
      //做事
      //do something;
   }
};

//②想要调用时
handler.sendEmptyMessage(0);

2.Thread

      new Thread(){
         public void run(){
            //在这里执行长耗时方法
            //do some hard thing;
         }
      }.start();

 

handle 和 thread都可以直接访问主线程的变量非常方便

//声明变量
private Button b1;
private ProgressDialog pd;
//定义Handler对象
private Handler handler =new Handler(){
   @Override
   public void handleMessage(Message msg){
      super.handleMessage(msg);

      pd.dismiss();       //直接访问主线程变量pd
   }
};
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
}
private void processThread(){
      pd= ProgressDialog.show(MainHandler.this, "同步", "正在同步…");
      new Thread(){
         public void run(){
            //在这里执行长耗时方法 
            //do some hard thing;

            handler.sendEmptyMessage(0); //直接访问主线程变量handler
         }
      }.start();
}

 

 

3.AsyncTask 

//...三个点表示可变长度参数列表
new AsyncTask<URL, Integer, Long>() {
  protected Long doInBackground(URL... urls) {
    long totalSize = 0;
    //first url is urls[0]
    return totalSize;
  }

  protected void onProgressUpdate(Integer... progress) {
    setProgressPercent(progress[0]);
  }

  protected void onPostExecute(Long result) {
    showDialog("Total Size is " + result );
  }
}.execute(url1, url2, url3);

4.Loader

待续

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页