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实例

介绍:使用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();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值