AsyncTask学习笔记

AsyncTask介绍

AsyncTask是一个轻量级的处理线程更新Android UI 的方式,AsyncTack是个抽象类,使用时应该继承它,它定义了3个泛型

 1. Params:启动任务执行时输入的参数
 2. Progress:后台任务完成时的数据类型
 3. Result:后台任务结束时返回的数据类型

AsyncTask使用

 1. 为上面三个泛型指定具体数据类型
 2. 必须实现doInBackground()方法
 3. 根据业务来实现不同的方法:onProgressUpdate  onPreExecute  onPostExecute方法
 4. 调用AnsyncTask子类实例

注:必须在UI线程中创建AsyncTask的实例
必须在UI线程中调用AsyncTask的excute方法
每个AsyncTask只能执行一次,否则会报错

AsyncTask方法调用顺序

 1. 首先调用onPreExecute方法,一般是初始化各种控件
 2. 执行onInbBackground执行目的任务
 3. 任务不断调用publishProgress更新进度,也就相当于调用了onProgressUpdate方法
 4. 任务完成调用onPostExecute并且把返回值传递给onPostExecute

AsyncTask学习笔记_第1张图片

AsyncTask实例

介绍:使用AsyncTask来下载并且显示到界面

java代码

package com.phone.hty.myapplication;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends AppCompatActivity {

    private TextView mMteTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mMteTextView = (TextView) findViewById(R.id.textView);
        Button button = (Button) findViewById(R.id.myButton);
        assert button != null;
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyAsyncStack myAsyncStack = new MyAsyncStack(MainActivity.this);
                try {
                    myAsyncStack.execute(new URL("http://110.65.7.96:8080/hty.txt"));
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            }
        });


    }
    class MyAsyncStack extends AsyncTask<URL, Integer, String> {
        ProgressDialog progressDialog;
        int length;
        Context mContext;


        public MyAsyncStack(Context context) {
            mContext = context;

        }

        /** * 描述:AsyncStack * 参数:URL * 形参: * 时间:2016/3/2714:18 */

        @Override
        protected String doInBackground(URL... params) {
            StringBuilder stringBuilder = new StringBuilder();
            try {
                URLConnection connection = params[0].openConnection();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
                        connection.getInputStream(), "utf-8"
                ));
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line + "\n");
                    length++;
                    publishProgress(length);
                }return stringBuilder.toString();


            } catch (IOException e) {
                e.printStackTrace();
            }


            return null;
        }

        /** * Runs on the UI thread before {@link #doInBackground}. * * @see #onPostExecute * @see #doInBackground */
        @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();


        }

        /** * Runs on the UI thread after {@link #publishProgress} is invoked. * The specified values are the values passed to {@link #publishProgress}. * * @param values The values indicating progress. * @see #publishProgress * @see #doInBackground */
        @Override
        protected void onProgressUpdate(Integer... values) {
            mMteTextView.setText("已经读取了" + values[0] + "行");
            progressDialog.setProgress(values[0]);
        }

        /** * <p>Runs on the UI thread after {@link #doInBackground}. The * specified result is the value returned by {@link #doInBackground}.</p> * <p/> * <p>This method won't be invoked if the task was cancelled.</p> * * @param s The result of the operation computed by {@link #doInBackground}. * @see #onPreExecute * @see #doInBackground * @see #onCancelled(Object) */
        @Override
        protected void onPostExecute(String s) {
            mMteTextView.setText(s);
            progressDialog.dismiss();
        }
    }
}

你可能感兴趣的:(UI,android,数据,AsyncTask)