Android 多线程断点续传-开源项目xutils3实现

来源:互联网 发布:如何删除mac系统 编辑:程序博客网 时间:2024/06/03 15:50

多线程断点续传,我采用xUtils3的第三方开源代码进行实现,实现起来就比较简单了。xUtils3的GitHub地址 ,当然最初的时候是xUtils(xUtils的GitHub地址),但是随着版本的更新,由于api发生很大的变化,就出现了xUtils3。当然我也与时俱进的体验了一把xUtils3的多线程(默认就是3个或者4个线程)断点续传。


xutils是前几年比较火得一个开源框架,主要分四个重要的模块:ViewUtils,HttpUtils,BitmapUtils,DbUtils,包含了很多实用的工具类,支持大文件上传,且有更全面的http请求协议支持,拥有灵活的Orm,支持事件注解且不受代码混淆影响。
但是Github上面的xutils已经很久没有更新了,并且随着Android版本的升级和人们开发软件思想的转变,xutils也暴露出了些许的问题,例如xutils对Android6.0的兼容性就不是特别好,所以还是建议大家使用比较新的xutils3。下面来看看官方(https://github.com/wyouflf/xUtils3)对xUtils3的介绍:

  • xUtils包含了很多实用的android工具;
  • xUtils支持超大文件(超过2G)上传,更全面的http请求协议支持(11种谓词),拥有更加灵活的ORM,更多的事件注解支持且不受混淆影响;
  • xUtils 最低兼容Android 4.0 (api level 14);
  • xUtils3变化较多所以建立了新的项目不在旧版(github.com/wyouflf/xUtils)上继续维护, 相对于旧版本: 
    • HTTP实现替换HttpClient为UrlConnection, 自动解析回调泛型, 更安全的断点续传策略;
    • 支持标准的Cookie策略, 区分domain, path;
    • 事件注解去除不常用的功能, 提高性能;
    • 数据库api简化提高性能, 达到和greenDao一致的性能;
    • 图片绑定支持gif(受系统兼容性影响, 部分gif文件只能静态显示), webp; 支持圆角, 圆形, 方形等裁剪, 支持自动旋转。

下面简单介绍一下如何在AS中使用第三方的xUtils3。当然这都是多余的介绍,因为xUtils3上有很详细的介绍

1)配置xUtils3

xUtils3的配置十分的简单:

1-1)使用Gradle构建时添加一下依赖即可

compile 'org.xutils:xutils:3.5.0'

如果使用eclipse可以点击下面链接下载aar文件, 然后用zip解压,取出jar包和so文件。

Github下载:https://github.com/wyouflf/xUtils3
JCenter下载:http://jcenter.bintray.com/org/xutils/xutils/
Maven下载1:http://central.maven.org/maven2/org/xutils/xutils/
Maven下载2:http://repo1.maven.org/maven2/org/xutils/xutils/

1-2)加入权限

<uses-permission android:name="android.permission.INTERNET"/><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  • 1
  • 2
  • 1
  • 2

1-3)创建Application

public class MyApp extends Application {    @Override    public void onCreate() {        super.onCreate();        x.Ext.init(this);        x.Ext.setDebug(false); //输出debug日志,开启会影响性能    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

1-4)在AndroidManifest文件中注册MyApp

<application    android:name=".MyApp"    ...</application>
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

xUtils3主要包含注解模块、网络模块、图片模块和数据库模块,

2)代码实现

2-1)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="com.guangkai.xutils.MainActivity">    <EditText        android:id="@+id/et_url"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="@string/et_hint_download_link" />    <Button        android:id="@+id/btn_download"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/btn_download_link" />    <ProgressBar        android:id="@+id/pb_download_status"        style="@android:style/Widget.ProgressBar.Horizontal"        android:layout_width="match_parent"        android:layout_height="wrap_content" /></LinearLayout>

2-2)string.xml

<resources>    <string name="app_name">MutilThreadDowload</string>    <string name="et_hint_download_link">请输入下载链接</string>    <string name="btn_download_link">下载</string>    </resources>


2-3)MainActivity.java

package com.guangkai.xutils;import android.os.Environment;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;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 editText_url;    private Button btn_download;    private ProgressBar pb_download_status;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //找到对应的控件        findView();        //初始化各个控件        initView();    }    private void initView() {        //初始化xutils        x.Ext.init(getApplication());        x.Ext.setDebug(BuildConfig.DEBUG);        //获取输入的链接        final String httpDownloadUrl = editText_url.getText().toString().trim();        //设置Button的监听器        btn_download.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                //使用xutils第三方开源项目进行多线程的断点续传                Log.e("MainActivity",httpDownloadUrl);                RequestParams params = new RequestParams(httpDownloadUrl);                params.setAutoResume(true);                params.setSaveFilePath(Environment.getExternalStorageState());                params.setAutoRename(true);                x.http().post(params, new Callback.ProgressCallback<File>(){                    @Override                    public void onSuccess(File result) {                        Toast.makeText(getApplicationContext(),"下载成功",Toast.LENGTH_SHORT).show();                    }                    @Override                    public void onError(Throwable ex, boolean isOnCallback) {                        Toast.makeText(getApplicationContext(),"下载失败",Toast.LENGTH_SHORT).show();                    }                    @Override                    public void onCancelled(CancelledException cex) {                    }                    @Override                    public void onFinished() {                    }                    @Override                    public void onWaiting() {                    }                    @Override                    public void onStarted() {                    }                    @Override                    public void onLoading(long total, long current, boolean isDownloading) {                        pb_download_status.setMax((int) total);                        pb_download_status.setProgress((int) current);                    }                });            }        });    }    private void findView() {        //网络连接地址        editText_url = (EditText) findViewById(R.id.et_url);        //下载按钮        btn_download = (Button) findViewById(R.id.btn_download);        //下载进度展示        pb_download_status = (ProgressBar) findViewById(R.id.pb_download_status);    }}

2-4)build.gradle

apply plugin: 'com.android.application'android {    compileSdkVersion 26    buildToolsVersion "26.0.0"    defaultConfig {        applicationId "com.guangkai.xutils"        minSdkVersion 15        targetSdkVersion 26        versionCode 1        versionName "1.0"        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"    }    buildTypes {        release {            minifyEnabled false            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'        }    }}dependencies {    compile fileTree(dir: 'libs', include: ['*.jar'])    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {        exclude group: 'com.android.support', module: 'support-annotations'    })    compile 'com.android.support:appcompat-v7:26.+'    compile 'com.android.support.constraint:constraint-layout:1.0.2'    compile 'org.xutils:xutils:3.5.0'    testCompile 'junit:junit:4.12'}

2-5)AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.guangkai.xutils">    <uses-permission android:name="android.permission.INTERNET" />    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />    <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">        <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>