Android--异步任务AsyncTask


 

 实例:使用异步任务从网络上下载


package com.example.xiaocool.anysctaskdemo;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URLConnection;


public class MainActivity extends ActionBarActivity {
    private TextView show;
    private Button download;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        show = (TextView) this.findViewById(R.id.show_down);
        download = (Button) this.findViewById(R.id.button);
        download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DownTask task = new DownTask(MainActivity.this);
                try {
                    /**
                     * 开始执行耗时的任务
                     */
                    task.execute(new URI("http://news.baidu.com/"));
                } catch (Exception E) {
                    E.printStackTrace();
                }

            }
        });
    }


    /**
     * Params  启动任务执行的输入参数的类型
     * Progress 后台任务完成的进度值得类型,
     * Result   后台执行任务完成后 返回结果的类型
     * 如果不需要指定类型 Void
     * <p/>
     * 重写的方法都有系统调用
     */
    class DownTask extends AsyncTask<URI, Integer, String> {

        ProgressDialog progressDialog;
        //定义记录已读取行的数量
        int hasRead = 0;
        Context mContext;

        public DownTask(Context context) {
            mContext = context;
        }

        /**
         * 后台线程将要完成的任务,该方法可以调用publishProgress(Progress value)更新任务的执行进度
         *
         * @param params
         * @return
         */
        @Override
        protected String doInBackground(URI... params) {
            StringBuilder sb = new StringBuilder();
            try {
                URLConnection conn = params[0].toURL().openConnection();
                //打开conn连接对应的输入流,包装成BufferReader 对象
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(conn.getInputStream(), "utf-8")
                );
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                    hasRead++;
                    //更新任务的执行进度
                    publishProgress(hasRead);
                }
                return sb.toString();
            } catch (Exception e) {
                e.printStackTrace();

            }
            return null;
        }

        /**
         * 在doInBackground方法中调用publishProgress(Progress value),更新任务的进度后,就会触发该方法
         *
         * @param values
         */
        @Override
        protected void onProgressUpdate(Integer... values) {
            show.setText("读取了"+values[0]);
            progressDialog.setProgress(values[0]);
        }

        /**
         * 该方法将在执行后台耗时程序时被调用,该方法用于完成一些初始化的准备工作,比如在界面上显示进度条
         */
        @Override
        protected void onPreExecute() {
            progressDialog = new ProgressDialog(mContext);
            progressDialog.setTitle("任务正在执行中!");
            progressDialog.setMessage("任务正在执行中,稍后!!");
            //取消按钮不可用
            progressDialog.setCancelable(false);
            progressDialog.setMax(202);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setIndeterminate(false);
            progressDialog.show();
        }

        /**
         * 当doInBackground方法完成后,系统会自动调用该方法 并将doInBackground()的返回值传给该方法
         *
         * @param s
         */
        @Override
        protected void onPostExecute(String s) {
            //返回HTML 页面的内容
            show.setText(s);
            progressDialog.dismiss();
        }
    }
}


你可能感兴趣的:(android,异步任务)