Android 异步任务

一、系统自带的
         listview.setonRefreshListener(new OnRefreshListener() {// 设置刷新监听
                 public void onRefresh() {
                          new AsyncTask() {
                                protected Void doInBackground(Void... params) {
                                          SystemClock.sleep(1000);
                                          data.add("刷新后添加的内容");
                                           return null;
                                }

                               @Override
                               protected void onPostExecute(Void result) {
                                        adapter.notifyDataSetChanged();
                                        listview.onRefreshComplete();
                               }
                          }.execute(null);
                  }
       });
二、自定义的异步任务
 1.定义异步任务工具类
  public abstract class MyAsyncTask {
           private Handler handler = new Handler(){
           public void handleMessage(android.os.Message msg) {
                    onPostExecute();
           };
  };
  public abstract void onPreExecute();   //后台任务执行之前提示用户的界面操作.
  public abstract void onPostExecute();  //后台任务执行之后 更新界面的操作
  public abstract void doInBackground(); //在后台执行的一个耗时的操作.
  public void execute(){
           onPreExecute();        // 耗时任务执行之前通知界面更新
           new Thread(){
                  public void run() {
                           doInBackground();
                           handler.sendEmptyMessage(0);
                  };
           }.start();   
  }
 }
 

 2.使用异步任务工具类
 new MyAsyncTask() {
       @Override
       public void onPreExecute() {


       }

  
      @Override
      public void onPostExecute() {
               adapter.notifyDataSetChanged();
               listview.onRefreshComplete();
      }
  
      @Override
      public void doInBackground() {
               SystemClock.sleep(1000);
               data.add("刷新后添加的内容");
               return null;
      }
 };

Android 异步任务

上一篇:win7下用PyInstaller把Python代码打包成exe文件


下一篇:程序媛也话Android 之 自定义控件(垂直方向滑动条)