android多文件上传或者下载框架

最近我看到一个老项目的代码,上传多个文件尽然用了让我忍无可忍的递归操作,即一个文件上传成功之后另一个文件才开始下载,而且还没有进度展示。
下面是本人整理的框架效果:


23.gif

(1)开启一个线程池,只允许同时三个线程同时进行,当一个线程执行完毕时排队等待的线程将进入线程池;
(2)图中三个线程的进度是一样的,因为代码中写死了,正常上传或者下载框架中都会有类似onLoading的方法,利用返回值计算出合理的进度;
(3)demo的代码也许没有最优化,可以根据自己的需求调整代码,使代码更加完善;

下面粘贴下代码:

MultiUploadActivity.java

package com.jiangxi.login.miltilyupload;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;

import java.util.ArrayList;

public class MultiUploadActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private MultiAdapter dzAdapter;
    private volatile boolean isRunning=false;//判断线程池是否运行 标志位
    private UploadUtil mUploadUtil;

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

        recyclerView = findViewById(R.id.recycler_view);


        //上传文件工具类
        mUploadUtil=new UploadUtil();

        final ArrayList<UploadBean> list = new ArrayList<>();
        list.add(new UploadBean(0, (byte) 0));
        list.add(new UploadBean(0, (byte) 0));
        list.add(new UploadBean(0, (byte) 0));
        list.add(new UploadBean(0, (byte) 0));
        list.add(new UploadBean(0, (byte) 0));
        list.add(new UploadBean(0, (byte) 0));
        list.add(new UploadBean(0, (byte) 0));
        list.add(new UploadBean(0, (byte) 0));
        list.add(new UploadBean(0, (byte) 0));
        list.add(new UploadBean(0, (byte) 0));
        list.add(new UploadBean(0, (byte) 0));
        list.add(new UploadBean(0, (byte) 0));
        list.add(new UploadBean(0, (byte) 0));


        dzAdapter = new MultiAdapter(this, list);
        recyclerView.setLayoutManager(new GridLayoutManager(MultiUploadActivity.this, 2));
        recyclerView.setHasFixedSize(false);
        recyclerView.setAdapter(dzAdapter);


        mUploadUtil.setOnUploadListener(new OnUploadListener() {
            @Override
            public void onAllSuccess() {
                isRunning=false;
            }

            @Override
            public void onAllFailed() {
                isRunning=false;
            }

            @Override
            public void onThreadProgressChange(int position, int percent) {

                list.get(position).setStatus((byte) 1);
                list.get(position).setUploadProgress(percent);
                dzAdapter.setDatas(list);
                dzAdapter.notifyItemChanged(position, list.get(position));
            }

            @Override
            public void onThreadFinish(int position) {
                list.get(position).setStatus((byte) 2);
                dzAdapter.setDatas(list);
                dzAdapter.notifyItemChanged(position, list.get(position));
            }

            @Override
            public void onThreadInterrupted(int position) {
                list.get(position).setStatus((byte) 3);
                dzAdapter.setDatas(list);
                dzAdapter.notifyItemChanged(position);

            }
        });


        if(!isRunning){
            startUpload(list);//开始上传
        }else{
            mUploadUtil.shutDownNow();//中断所有线程的执行
        }

    }


    private void startUpload(ArrayList<UploadBean> list){
        isRunning=true;

        mUploadUtil.submitAll(MultiUploadActivity.this, list);
    }
}

MultiAdapter.java

package com.jiangxi.login.miltilyupload;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;


public class MultiAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private List<UploadBean> mData;
    private Context mContext;
    private OnItemClickLitener mOnItemClickLitener;

    public MultiAdapter(Context context, List<UploadBean> mData) {
        this.mContext = context;
        this.mData = mData;
    }

    @Override
    public int getItemViewType(int position) {
        //防止滑动时图片混乱的问题
        return position;
    }

    /**
     * 设置
     * @param mData
     */
    public void setDatas(List<UploadBean> mData){
        this.mData = mData;
    }

    @Override
    public int getItemCount() {
        return mData != null ? mData.size() : 0;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position, @NonNull List<Object> payloads) {
        onBindViewHolder(holder, position);
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        UploadBean dataListBean = mData.get(position);

        dealUploadText(((ViewHolder) holder).tv_present, dataListBean);

        //如果设置了回调,则设置点击事件
        holder.itemView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mOnItemClickLitener != null) {
                    if(mData != null && mData.size() > 0){
                        mOnItemClickLitener.onItemClick(holder.itemView, position);
                    }
                }
            }
        });

    }

    /**
     * 处理进度条文本
     * @param tv_present
     * @param dataListBean
     */
    private void dealUploadText(TextView tv_present, UploadBean dataListBean){
        if(dataListBean == null){
            return;
        }
        if(dataListBean.getStatus() == 1){
            //如果正在上传中
            tv_present.setVisibility(View.VISIBLE);
            tv_present.setText("上传进度:"+dataListBean.getUploadProgress() + "%");
        }else if(dataListBean.getStatus() == 2){
            tv_present.setVisibility(View.VISIBLE);
            tv_present.setText("上传完成");
        }else if(dataListBean.getStatus() == 3){
            tv_present.setVisibility(View.VISIBLE);
            tv_present.setText("上传失败");
        }else {
            tv_present.setVisibility(View.GONE);
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(mContext).inflate(R.layout.upload_item, parent, false);
        ViewHolder holder = new ViewHolder(itemView);
        return holder;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView tv_present;

        public ViewHolder(View itemView) {
            super(itemView);
            tv_present = itemView.findViewById(R.id.tv_present);
        }
    }


    public interface OnItemClickLitener {
        void onItemClick(View view, int position);
    }

    public void setOnItemClickLitener(OnItemClickLitener mOnItemClickLitener) {
        this.mOnItemClickLitener = mOnItemClickLitener;
    }


}

UploadBean.java

package com.jiangxi.login.miltilyupload;

public class UploadBean {

    private int uploadProgress;// 上传进度

    private byte status;//0:默认 1:正在上传 2:上传完成 3:上传失败

    public UploadBean(int uploadProgress, byte status) {
        this.uploadProgress = uploadProgress;
        this.status = status;
    }

    public int getUploadProgress() {
        return uploadProgress;
    }

    public void setUploadProgress(int uploadProgress) {
        this.uploadProgress = uploadProgress;
    }

    public byte getStatus() {
        return status;
    }

    public void setStatus(byte status) {
        this.status = status;
    }
}

UploadUtil.java(在任何时候都要养成写工具类的习惯)

package com.jiangxi.login.miltilyupload;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class UploadUtil {
    //线程进度回调
    private final static int THREAD_PROGRESS_CODE=100;
    //线程完成
    private final static int THREAD_FINISH_CODE=101;
    //线程被中断
    private final static int THREAD_INTERRUPT_CODE=102;
    //所有线程完成
    private final static int THREAD_ALL_SUCCESS_CODE=103;
    //所有线程执行失败
    private final static int THREAD_ALL_FAILED_CODE=104;
    //handler传递进度值
    private final static String THREAD_PERCENT="THREAD_PERCENT";
    //handler传递position值
    private final static String THREAD_POSITION="THREAD_POSITION";
    //线程池核心数
    private int threadCore=3;
    //线程池
    private ExecutorService executor;
    //成功数量
    int successCount = 0;
    //失败数量
    int failedCount = 0;

    private OnUploadListener uploadListener;
    private UploadHandler handler;

    public UploadUtil(){
        init();
    }

    public UploadUtil(int threadCore){
        this.threadCore=threadCore;
        init();
    }

    public void setOnUploadListener(OnUploadListener uploadListener){
        this.uploadListener=uploadListener;
    }

    public void init(){
        handler=new UploadHandler(this);
        successCount = 0;
        failedCount = 0;
    }

    public void shutDownNow(){
        //中断所有线程的执行
        executor.shutdownNow();
    }

    public void submitAll(Activity mContext, final ArrayList<UploadBean> list){

        executor = Executors.newFixedThreadPool(threadCore);


        int i = 0;
        //遍历文件
        for (UploadBean uploadBean : list) {

            final Bundle bundle=new Bundle();
            bundle.putInt(THREAD_POSITION,i);
            i++;
            executor.submit(new UploadFile(mContext,i, list, new OnThreadResultListener(){
                @Override
                public void onProgressChange(final int percent) {
                    bundle.putInt(THREAD_PERCENT,percent);
                    Message.obtain(handler,THREAD_PROGRESS_CODE,bundle).sendToTarget();
                }

                @Override public void onFinish() {
                    successCount++;
                    if(successCount == list.size()){
                        successCount = 0;
                        failedCount = 0;
                        handler.sendEmptyMessage(THREAD_ALL_SUCCESS_CODE);
                    }
                    Message.obtain(handler,THREAD_FINISH_CODE,bundle).sendToTarget();
                }

                @Override public void onInterrupted() {
                    failedCount++;
                    if(successCount + failedCount == list.size()){
                        successCount = 0;
                        failedCount = 0;
                        handler.sendEmptyMessage(THREAD_ALL_FAILED_CODE);
                    }
                    Message.obtain(handler,THREAD_INTERRUPT_CODE,bundle).sendToTarget();
                }
            }));
        }
        //关闭线程池
        executor.shutdown();
    }

    private static class UploadHandler extends Handler {//静态内部类+弱引用防止内存泄漏
        private WeakReference<UploadUtil> weakReference;
        private UploadHandler(UploadUtil object){
            super(Looper.getMainLooper());//执行在UI线程
            weakReference=new WeakReference<>(object);
        }

        @Override public void handleMessage(Message msg){
            UploadUtil uploadUtil=weakReference.get();
            if(uploadUtil!=null){
                Bundle data= (Bundle) msg.obj;
                int position;
                int percent;
                switch (msg.what){
                    case THREAD_PROGRESS_CODE:
                        position=data.getInt(THREAD_POSITION);
                        percent=data.getInt(THREAD_PERCENT);
                        uploadUtil.uploadListener.onThreadProgressChange(position,percent);
                        break;
                    case THREAD_FINISH_CODE:
                        position=data.getInt(THREAD_POSITION);
                        uploadUtil.uploadListener.onThreadFinish(position);
                        break;
                    case THREAD_INTERRUPT_CODE:
                        position=data.getInt(THREAD_POSITION);
                        uploadUtil.uploadListener.onThreadInterrupted(position);
                        break;
                    case THREAD_ALL_SUCCESS_CODE:
                        uploadUtil.uploadListener.onAllSuccess();
                        break;
                    case THREAD_ALL_FAILED_CODE:
                        uploadUtil.uploadListener.onAllFailed(); break;
                }
            }
        }
    }
}

UploadFile.java

package com.jiangxi.login.miltilyupload;

import android.app.Activity;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.CountDownLatch;

public class UploadFile implements Runnable {


    private String fileName;//本地文件的参数:// 文件名

    private OnThreadResultListener listener;//任务线程回调接口
    private int percent=0;//进度
    private Activity mContext;

    private ArrayList<UploadBean> list;

    int index = 0;

    private CountDownLatch countDownLatch = new CountDownLatch(1);

    public UploadFile(Activity mContext, int index, ArrayList<UploadBean> list, OnThreadResultListener listener){
        this.list = list;
        this.listener=listener;
        this.mContext = mContext;
        this.index = index;
    }

    @Override
    public void run() {

        //上传线程
        final TimerTask task = new TimerTask() {
            @Override
            public void run() {
                if(percent < 0){
                    listener.onInterrupted();
                }else if(percent < 100){
                    percent += 1;
                    listener.onProgressChange(percent);
                }else if(percent >= 100){
                    percent = 0;
                    this.cancel();
                    //继续执行线程
                    countDownLatch.countDown();
                    listener.onFinish();
                }
            }
        };
        Timer timer = new Timer();
        timer.schedule(task, 1000, 100);

        try {
            //等待
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

OnThreadResultListener.java

package com.jiangxi.login.miltilyupload;

public interface OnThreadResultListener {
    void onProgressChange(int percent);//进度变化回调
    void onFinish();//线程完成时回调
    void onInterrupted();//线程被中断回调
}

OnUploadListener.java

package com.jiangxi.login.miltilyupload;

public interface OnUploadListener {//主线程回调
    void onAllSuccess();
    void onAllFailed();
    void onThreadProgressChange(int position,int percent);
    void onThreadFinish(int position);
    void onThreadInterrupted(int position);
}

upload_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp">

    <TextView
        android:id="@+id/tv_present"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textSize="20sp"
        android:visibility="visible"
        android:text="准备开始"/>

</RelativeLayout>

以上就是全部代码了。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,772评论 6 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,458评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,610评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,640评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,657评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,590评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,962评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,631评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,870评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,611评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,704评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,386评论 4 319
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,969评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,944评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,179评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,742评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,440评论 2 342

推荐阅读更多精彩内容

  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明先生_x阅读 15,967评论 3 119
  • <!doctype html>html文档开头标注,表明支持最新html规范和标准,可以理解为活的标准,由万维网协...
    向着远方奔跑阅读 227评论 0 0
  • 如果不动,你永远都是观众
    平小主阅读 134评论 0 1
  • 每天从睁眼开始,看见的东西东西,每日的习惯,规划的事项,这一切看似合情合理,背后却是暗藏杀机。这个隐杀手就是观点。...
    秦家炎阅读 197评论 0 2
  • 我遇见你像阿米尔遇见索拉雅从此每一天于我皆是雅尔达 那时年纪小 习惯顾盼神飞 淋雨是莫名欢喜 晴天也可以湿漉漉 那...
    胥子灵阅读 409评论 0 0