<AsyncTask> 查看网页源代码

志向是天才的幼苗,经过热爱劳动的双手培育,在肥田沃土里将成长为粗壮的大树。不热爱劳动,不进行自我教育,志向这棵幼苗也会连根枯死.


*按钮的点击事件的方法里面, 只是创建一个 DownTask实例

package com.test.asynctaskdemo;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
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;


/**
 * (异步任务) AsyncTask
 * <p/>
 * 为了解决子线程不能更新 UI线程的问题,Android 提供了以下几种解决方案.
 * 1.使用handler 实现线程之间的通信
 * 2.Activity.runOnUiThread(Runnable)
 * 3.View.post(Runnable)
 * 4.View.postDelayed(Runnable, long);
 * 5.AsyncTask
 */

public class AsyncTaskActivity extends Activity {
    TextView textView;
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_async_task);

        textView = (TextView) findViewById(R.id.tv_html);
        btn = (Button) findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DownTask downTask = new DownTask();
                try {
                    //必须在主线程 调用该方法
                    downTask.execute(new URL("https://www.baidu.com"));

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

    private class DownTask extends AsyncTask<URL, Integer, String> {

        //可变参的输入参数必须和AsyncTask.execute();对应

        ProgressDialog progressDialog;

        int hasRead = 0;     //定义记录应经读取的行数

        Context mContext;

        public void DownTask(Context ctx) {
            mContext = ctx;
        }


        @Override
        protected String doInBackground(URL... params) {

            StringBuilder sb = new StringBuilder();

            try {
                URLConnection conn = params[0].openConnection();

                //打开conn对应的输入流,并把它封装成 BufferedReader

                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 (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            textView.setText(result);
            progressDialog.dismiss();
        }
        @Override
        protected void onPreExecute() {
            progressDialog = new ProgressDialog(AsyncTaskActivity.this);
            progressDialog.setTitle("标题 任务正在执行中");
            progressDialog.setMessage("内容 任务正在执行中, 敬请期待...");
            progressDialog.setCancelable(false);  //设置对话框不能取消
            progressDialog.setMax(200);  //设置最大值

            //设置进度条样式
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

            //设置对话框是否显示 进度
            progressDialog.setIndeterminate(true);
            progressDialog.show();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            //更新进度
            textView.setText("已经读取了[" + values[0] + " ]行");
            progressDialog.setProgress(values[0]);
        }
    }
}

切记记得在清单文件中 加上联网权限

布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.test.asynctaskdemo.AsyncTaskActivity">

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="下载网页代码" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/btn">

        <TextView
            android:id="@+id/tv_html"
            android:layout_width="match_parent"
            android:layout_height="match_parent"

            android:layout_margin="3dp"
            android:text="Hello World!" />
    </ScrollView>
</RelativeLayout>

“`

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值