首页 > 编程语言 > Android基于开源项目xutils3实现下载
2020
11-22

Android基于开源项目xutils3实现下载

上一次自己写了一个多线程断点续传下载的demo,过于麻烦,bug超多,所以我学习使用xutils来完成此功能。

先将xutils依赖搭建好(上一篇博客已经具体写了方法)

先看看效果图:

下面开始代码的逻辑:

在xutils3以前使用HttpUtils新建对象即可使用,3以后取消了HttpUtils,具体方法请看代码。

首先创建布局activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
  android:orientation="vertical"
  tools:context=".MainActivity">

  <EditText
    android:id="@+id/et_path"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="请输入下载路径"
    android:text="http://10.173.29.234/gp.apk" />

  <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="下载"
    android:onClick="click"/>

  <ProgressBar
    android:id="@+id/progressBar"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

</LinearLayout>

然后MainActivity.java:

import android.app.Activity;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;

public class MainActivity extends AppCompatActivity {

  private EditText et_path;
  private ProgressBar pb;
  //动态获取权限
  private static final int REQUEST_EXTERNAL_STORAGE = 1;
  private static String[] PERMISSIONS_STORAGE = {
      "android.permission.READ_EXTERNAL_STORAGE",
      "android.permission.WRITE_EXTERNAL_STORAGE" };
  private String fileName;
  private String appName;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //动态获取权限
    verifyStoragePermissions(this);

    x.view().inject(this);

    et_path = findViewById(R.id.et_path);
    pb = findViewById(R.id.progressBar);


  }

  //点击按钮下载(断点续传)
  public void click(View view) {

    //拿到路径
    String path = et_path.getText().toString().trim();
    fileName = getFileName(path);
    RequestParams params = new RequestParams(path);
    params.setSaveFilePath(fileName);
    params.setAutoRename(true);
    x.http().get(params, new Callback.ProgressCallback<File>() {

      @Override
      public void onWaiting() {

      }

      @Override
      public void onStarted() {

      }

      @Override
      public void onLoading(long total, long current, boolean isDownloading) {
        //totle代表总进度,current代表当前进度
        pb.setMax((int) total);
        pb.setProgress((int) current);
        System.out.println("测试1");

      }


      @Override
      public void onSuccess(File result) {
        System.out.println("下载完成");
        Toast.makeText(getApplicationContext(), "下载成功", Toast.LENGTH_SHORT).show();

      }

      @Override
      public void onError(Throwable ex, boolean isOnCallback) {
        System.out.println("测试2");

      }

      @Override
      public void onCancelled(CancelledException cex) {
        System.out.println("测试3");

      }

      @Override
      public void onFinished() {
        System.out.println("测试4");

      }
    });


  }
  //动态获取权限
  public static void verifyStoragePermissions(Activity activity) {

    try {
      //检测是否有写的权限
      int permission = ActivityCompat.checkSelfPermission(activity,
          "android.permission.WRITE_EXTERNAL_STORAGE");
      if (permission != PackageManager.PERMISSION_GRANTED) {
        // 没有写的权限,去申请写的权限,会弹出对话框
        ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  //获取文件名-->"http://10.173.29.234/test.exe"
  public String getFileName(String path) {
    int start = path.lastIndexOf("/") + 1;
    appName = path.substring(start);
//    String fileName = Environment.getExternalStorageDirectory().getPath()+"/"+subString;
    String fileName = "/sdcard/file/"+ appName;
    return fileName;

  }
}

第53行注意x.http().get(params, new Callback.ProgressCallback<File>(){};<>中要写File,因为下载的是一个文件,否则文件不会下载下来。

还要加上权限:

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。

编程技巧