AsyncTask - 文件下载

package com.example.day3;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class AsyncTaskTwoActivity extends AppCompatActivity {

  private TextView info;
  private ProgressBar progressBar;

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

    info = findViewById(R.id.info);
    progressBar = findViewById(R.id.progress);

    findViewById(R.id.download).setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        download();
      }
    });
  }

  String apkUrl = "https://dldir1.qq.com/weixin/android/weixin673android1360.apk";

  private void download() {
    //void
    @SuppressLint("StaticFieldLeak") AsyncTask<String, Integer, File> asyncTask =
        new AsyncTask<String, Integer, File>() {
          //子线程下载
          @Override protected File doInBackground(String... strings) {
            Log.i("TEST", "doInBackground");
            try {
              URL url = new URL(strings[0]);
              HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
              int responseCode = urlConnection.getResponseCode();
              if (responseCode == 200) {
                //将流转换成String
                //一边读流一边写
                //File file = saveFile(urlConnection.getInputStream());

                File file = new File(getCacheDir(), "downloadfile.apk");
                FileOutputStream fos = new FileOutputStream(file);
                InputStream is = urlConnection.getInputStream();

                final int totalCount = urlConnection.getContentLength();
                byte[] buf = new byte[10240];
                int count = 0;
                for (int i = is.read(buf); i != -1; i = is.read(buf)) {
                  //写数据到文件
                  fos.write(buf, 0, i);

                  //发布进度
                  count = count + i;
                  //当前进度 文件总大小
                  publishProgress(count, totalCount);
                }

                //关闭流
                fos.flush();
                fos.close();

                return file;
              }
            } catch (MalformedURLException e) {
              e.printStackTrace();
            } catch (IOException e) {
              e.printStackTrace();
            }
            return null;
          }

          //进度更新了 主线程
          @Override protected void onProgressUpdate(Integer... values) {
            info.setText(values[0] + "  /  " + values[1]);

            //progressBar.setProgress((int)((100f / values[1]) * values[0]));
            progressBar.setProgress((int)((values[0]*1.0f / values[1]) * 100));
          }

          @Override protected void onPreExecute() {
            //先于onPostExecute调用
            Log.i("TEST", "onPreExecute");
          }

          //主线程接收
          @Override protected void onPostExecute(File file) {
            String filePath = file.getAbsolutePath();
            Log.i("TEST", "onPostExecute: " + file.getAbsolutePath());

            Intent i = new Intent(Intent.ACTION_VIEW);
            //if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // 7.0+以上版本
            //   Uri apkUri = getUriForFile(mContext, mContext.getApplicationContext().getPackageName() + ".provider", apkfile); //与manifest中定义的provider中的authorities="com.xinchuang.buynow.fileprovider"保持一致
            //  i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            //  i.setDataAndType(apkUri, "application/vnd.android.package-archive");
            //  i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //} else {
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.setDataAndType(Uri.parse("file://" + file.toString()),
                "application/vnd.android.package-archive");
            //}
            startActivity(i);
          }
        }.execute(apkUrl);
  }

  private File saveFile(InputStream is) throws IOException {
    //getCacheDir() 应用缓存目录      ;    文件名
    File file = new File(getCacheDir(), "downloadfile.apk");
    //把文件 和 输出流 关联起来
    FileOutputStream fos = new FileOutputStream(file);

    byte[] buf = new byte[10240];
    for (int i = is.read(buf); i != -1; i = is.read(buf)) {
      //写数据到文件
      fos.write(buf, 0, i);
    }

    //关闭流
    fos.flush();
    fos.close();

    return file;
  }
}

**

## 布局文件

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

  <ProgressBar
      android:id="@+id/progress"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      app:layout_constraintBottom_toTopOf="@id/download"
      app:layout_constraintLeft_toLeftOf="parent"
      app:layout_constraintRight_toRightOf="parent"
      app:layout_constraintTop_toTopOf="parent"
      style="@style/Base.Widget.AppCompat.ProgressBar.Horizontal"
      android:max="100"
      android:progress="0"
      />

  <TextView
      android:id="@+id/info"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      app:layout_constraintBottom_toTopOf="@id/download"
      app:layout_constraintLeft_toLeftOf="parent"
      app:layout_constraintRight_toRightOf="parent"
      app:layout_constraintTop_toTopOf="parent"
      />

  <Button
      android:id="@+id/download"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:text="下载"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintLeft_toLeftOf="parent"
      app:layout_constraintRight_toRightOf="parent"
      />

</android.support.constraint.ConstraintLayout>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值