说实话,笔者是菜鸟,之前有做过一次获取利用AsyncTask获取源代码的实验,但是不成功,今天刚好有兴趣,看了一下《疯狂Android讲义》对应AsyncTask的知识点,了解了AsyncTask类的基本用法,琢磨了一下,终于成功,所以来这里分享一下,也希望可以帮到有需要的小伙伴,下面是具体代码

MainActivity.java

package poison.project.asynctaskexperiment;

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

public class MainActivity extends Activity{
    private TextView show;  //定义需要获取的组件
    private Button btn;

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

        show=(TextView)findViewById(R.id.show);
        btn=(Button)findViewById(R.id.button);
        
        //为按钮绑定事件响应方法
        btn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                try {
                    download();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }
    //重写该方法,为界面的按钮提供事件响应方法
    public void download() throws  MalformedURLException{
        CodeTask task=new CodeTask(this);
        task.execute(new URL("https://www.baidu.com/"));
    }

    class CodeTask extends AsyncTask<URL,Integer,String>{
        //可变长的输入参数,与AsyncTask.exucute()对应
        ProgressDialog progressDialog;
        //定义记录已读取行的数量
        int hasRead=0;
        Context mContext;

        public CodeTask(Context ctx){
            mContext=ctx;
        }
        //完成实际的下载任务
        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(Exception e){
                e.printStackTrace();
            }
            return null;
        }
        @Override
        protected  void onPostExecute(String result){
            //返回HTML页面内容
            show.setText(result);
            progressDialog.dismiss();
        }

        //负责在下载的时候显示一个进度条
        @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();
        }

        //负责在下载的过程更新下载进度的进度条值
        @Override
        protected  void onProgressUpdate(Integer... values){
            //更新进度
            show.setText("已经读取了【"+values[0]+"】行!");
            progressDialog.setProgress(values[0]);
        }
    }
}

 上面程序其实很容易理解,它只是按照了AsyncTask一般使用步骤,具体不了解的可百度AsyncTask的用法,都有详细的介绍

该程序的重点是实现AsyncTask的子类,实现该该子类时实现了如下四个方法:

doInBackground():该方法完成实际的下载任务,返回一个结果给onPostExecute()方法

onPreExecute():该方法负责在下载开始的时候显示一个进度条

onProgressUppdate():该方法负责更新下载进度的进度条的值

onPostExecute():该方法负责在下载完成后,将下载代码显示出来

由于该程序使用了网络编程从网络上下载数据,需要访问网络,所以要在AndroidMainfest.xml文件中声明以下权限:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

如果读者安装的是Android9.0的话,还需要再<application... />中加上

android:usesCleartextTraffic="true"

笔者用的就是Android9.0,所以在此特别提醒,希望小伙伴们可以避开我犯过的错

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="poison.project.asynctaskexperiment" >

    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true">
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

布局文件,这部分比较简单,在这里就不做讲解了

 

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/show"
        android:layout_width="match_parent"
        android:layout_height="500dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="160dp"
        android:layout_marginTop="20dp"
        android:text="下载"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/show" />

</android.support.constraint.ConstraintLayout>

笔者水平有限,只能凭己所学做粗略说明,本程序亲测有效,截图如下:

android 简单获得网页源码 android获取网页源码并解析_xml