Android学习笔记1-AsyncTask的用法

这里记录《疯狂Android讲义》上面的一个例子。

public class AsyncTaskTest extends AppCompatActivity {

    private TextView show;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_async_task_test);
        show = (TextView)findViewById(R.id.show);
    }

    public void download(View view) throws MalformedURLException{
        //必须在UI线程中创建AsyncTask的实例
        //必须在UI线程中调用execute()方法
        //每个AsyncTask只能被执行一次
        DownTask task = new DownTask(this);
        task.execute(new URL("http://www.crazyit.org/ethos.php"));
    }

    class DownTask extends AsyncTask{

        ProgressDialog pdialog;
        int hasRead = 0;
        Context mContext;

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

        @Override
        protected void onPreExecute() {
            pdialog = new ProgressDialog(mContext);
            pdialog.setTitle("Task is in progress");
            pdialog.setMessage("in progress, please wait ....");
            //设置对话框不能“取消”按钮
            pdialog.setCancelable(false);
            pdialog.setMax(202);
            pdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            //设置对话框的进度条是否显示进度
            pdialog.setIndeterminate(false);
            pdialog.show();
        }

        @Override
        protected String doInBackground(URL... params) {
            StringBuilder sb = new StringBuilder();
            try{
                URLConnection conn = params[0].openConnection();
                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);//更新任务的执行进度, 该方法将会触发onProgressUpdate()
                }
                //返回值将传递给onPostExecute()方法
                return sb.toString();
            }catch (Exception e){
                e.printStackTrace();
            }
            return  null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            show.setText("已经读取了【" + values[0] + "】行");
            pdialog.setProgress(values[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            show.setText(result);//接收doInBackground()方法的返回值
            pdialog.dismiss();
        }

    }
}

以上代码来源于《疯狂Android讲义》,借鉴学习

你可能感兴趣的:(Android学习笔)