Mainactivity package com.example.asynctask; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private ProgressBar mprogressBar; private Button mDownloadbutton; private TextView mresultTextview; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //设置初始化视图 initView(); //设置点击监听 setListener(); //初始化UI数据 setDate(); } private void setDate() { mresultTextview.setText("准备下载"); mDownloadbutton.setText("点击下载"); mprogressBar.setProgress(0); } private void setListener() { mDownloadbutton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //下载的事情 DownloadAsynctask downloadAsynctask=new DownloadAsynctask(); downloadAsynctask.execute("https://mp.yuncheapp.cn/admin/html/media/user/account.html"); } }); } //初始化视图 private void initView() { mprogressBar= (ProgressBar) findViewById(R.id.progressBar); mDownloadbutton = (Button) findViewById(R.id.button); mresultTextview = (TextView) findViewById(R.id.textview); } public class DownloadAsynctask extends AsyncTask<String,Integer,Boolean>{ String mFilePath; //在异步任务之前,在主线程中 @Override protected void onPreExecute() { super.onPreExecute(); mDownloadbutton.setText("下载中"); mresultTextview.setText("下载中"); mprogressBar.setProgress(0); //可操作UI } //继承后的方法,在另一个线程中处理事件 @Override //String是入参类型,返回类型(出参)为Boolean类型,是结果,与继承时写的三个类型一样,第一个是入参,第三个是结果 //这个方法里面就是在后台进行操作 //String... strings表示可变参数,代表长度是可变的 //execute("imooc","good");,里面的imooc与good就代表strings //进度就是在这个里面使用的 protected Boolean doInBackground(String... strings) { if(strings !=null && strings.length>0){ String apkurl=strings[0]; try { //构造URL URL url=new URL(apkurl); //构造链接并打开 URLConnection urlConnection=url.openConnection(); //这个链接的链接输出的INputstream把他拿到 InputStream inputStream=urlConnection.getInputStream(); //获得下载内容的总长度 int contentlength=urlConnection.getContentLength(); //下载地址准备 // Environment.getExternalStorageDirectory()这个方法获取地址,永远是正确的 //File.separator表示斜杠 mFilePath= Environment.getExternalStorageDirectory() + File.separator+"imooc.apk"; //对下载地址进行处理 File apkFile=new File(mFilePath); //如果它存在 if(apkFile.exists()){ //对他进行删除 boolean result=apkFile.delete(); //如果删除失败 if(!result){ return false; } } //已下载的大小 int downloadsize=0; // byte[] bytes=new byte[1024]; int length; //创建一个输出管道 OutputStream outputStream=new FileOutputStream(mFilePath); //直道挖完以后,才会=-1 //inputStream .read(bytes)表示挖一次就读一次 while((length=inputStream .read(bytes))!=-1){ //把挖到的数放进bytes(文件管道)里面,write表示每次都写,从0开始,写道这次循环的长度 outputStream.write(bytes,0,length); downloadsize+=length; //发送进度,乘以100是为了化为百分比 publishProgress(downloadsize*100/contentlength); } //把他关掉,否则可能造成内存的溢出 inputStream.close(); outputStream.close(); //一旦出了异常,就采取false打出来 } catch (IOException e) { e.printStackTrace(); return false; } }else{ return false; } return true; } //当执行完了以后,他会把上一个执行的doInBackground里面的参数传过来 //也是在主线程中,执行结果处理 @Override protected void onPostExecute(Boolean aBoolean) { super.onPostExecute(aBoolean); mDownloadbutton.setText(aBoolean? "下载完成":"下载失败"); mresultTextview.setText(aBoolean? "下载完成"+mFilePath:"下载失败"); } //当我们的进度变化的时刻,可以在这里体现出来,进行处理 //Integer... values进度条就是我们在AsyncTask定义的第二个参数,即Integer @Override protected void onProgressUpdate(Integer... values) { //在这里收到抛出来的进度,然后进行处理 super.onProgressUpdate(values); if (values != null && values.length > 0) { mprogressBar.setProgress(values[0]); } } //这个方法是进行取消,但是他这个取消没办法将正在异步线程中的任务进行取消,而是在异步进程完成后没办法进入主线程 @Override protected void onCancelled(Boolean aBoolean) { super.onCancelled(aBoolean); } activity_main
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:orientation="vertical"> <ProgressBar android:id="@+id/progressBar" style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="15dp" android:layout_marginStart="4dp" android:layout_marginTop="40dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="156dp" android:layout_marginBottom="26dp" android:text="点击下载" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="hello world:imooc" android:layout_marginLeft="160dp" android:id="@+id/textview"/> </LinearLayout>