android——文件斷點(diǎn)續(xù)傳下載(二)

GIF.gif

上篇博客寫的是單個(gè)文件單個(gè)線程的斷點(diǎn)續(xù)傳下載(文件斷點(diǎn)續(xù)傳下載(一)),這里是在之前的基礎(chǔ)上進(jìn)行了擴(kuò)展,變成了多文件,多線程同時(shí)下載/暫停,同時(shí)添加了通知欄下載狀態(tài)顯示,雖然代碼是基于之前的,還是做了不少改動(dòng)。
1、activity中顯示的是一個(gè)列表,點(diǎn)擊事件的觸發(fā)是在列表的條目中,就需要在點(diǎn)擊開(kāi)始時(shí),將點(diǎn)擊事件通過(guò)接口回調(diào)到activity中,進(jìn)行權(quán)限的申請(qǐng)
2、當(dāng)多任務(wù)、多線程同時(shí)操作時(shí),利用BroadcastReceiver進(jìn)行通信會(huì)導(dǎo)致界面不有點(diǎn)卡,就改用了Messenger+Handler進(jìn)行通信
3、需要對(duì)Notification做8.0的適配
4、利用TimerTask、Timer進(jìn)行消息的輪詢
5、改用線程池對(duì)線程的管理
先看下列表適配器中的邏輯,很簡(jiǎn)單,

public class FileListAdapter extends BaseAdapter {
    private Context mContext;
    private List<FileInfo> list;

    public FileListAdapter(Context context, List<FileInfo> list) {
        this.mContext = context;
        this.list = list;
    }
    @Override
    public int getCount() {
        return list == null ? 0 : list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        final FileInfo fileInfo = list.get(position);
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = LayoutInflater.from(mContext).inflate(R.layout.file_list_adapter_item, parent, false);
            viewHolder.tvFileName = convertView.findViewById(R.id.tv_file_name);
            viewHolder.progressBar = convertView.findViewById(R.id.progress_bar);
            viewHolder.btnStop = convertView.findViewById(R.id.btn_stop);
            viewHolder.btnStart = convertView.findViewById(R.id.btn_start);

            viewHolder.progressBar.setMax(100);
            viewHolder.tvFileName.setText(fileInfo.fileName);
            viewHolder.btnStart.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (listener != null) {
                        listener.doStart(position, fileInfo);
                    }
                }
            });
            viewHolder.btnStop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (listener != null) {
                        listener.doStop(position, fileInfo);
                    }
                }
            });
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        viewHolder.progressBar.setProgress(fileInfo.finished);

        return convertView;
    }

    /**
     * 更新列表項(xiàng)中條目下載進(jìn)度
     */
    public void updateProgress(List<FileInfo> fileInfos) {
        this.list = fileInfos;
        notifyDataSetChanged();
    }

    class ViewHolder {
        TextView tvFileName;
        ProgressBarView progressBar;
        Button btnStop, btnStart;
    }

    private onItemClick listener;

    public void setOnItemClick(onItemClick listener) {
        this.listener = listener;
    }

    public interface onItemClick {
        /**
         * 開(kāi)始下載
         *
         * @param position
         */
        void doStart(int position, FileInfo fileInfo);

        /**
         * 暫停下載
         *
         * @param position
         */
        void doStop(int position, FileInfo fileInfo);
    }
}

不過(guò)有點(diǎn)細(xì)節(jié)需要注意的,賦值一次后不需要變動(dòng)的數(shù)據(jù),就不需要數(shù)據(jù)復(fù)用了,這樣會(huì)提高一些性能,這里文件名稱的賦值、ProgressBar的初始化、開(kāi)始/暫停的點(diǎn)擊事件就沒(méi)有進(jìn)行復(fù)用,然后在回調(diào)事件中去做權(quán)限的申請(qǐng)、開(kāi)啟下載/暫停下載的邏輯處理。
之前是通過(guò)startService的方式開(kāi)啟一個(gè)Service的,這里沒(méi)有采用該方式,用的是綁定服務(wù)的方式,在onCreate()方法中綁定一個(gè)Service;

//綁定service
Intent intent = new Intent(this, DownLoadService.class);
bindService(intent, serviceConnection, Service.BIND_AUTO_CREATE);

Service綁定后,就會(huì)回調(diào)ServiceConnection中的onServiceConnected()方法,在該方法中利用Messenger同時(shí)在Service的onBind()方法中也利用Messenger進(jìn)行activity和Service數(shù)據(jù)通信雙向綁定;

ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //綁定回調(diào)
            //獲得service中的Messenger
            mServiceMessenger = new Messenger(service);
            //創(chuàng)建activity中的Messenger
            Messenger messenger = new Messenger(mHandler);
            //創(chuàng)建一個(gè)消息
            Message message = new Message();
            message.what = DownLoadService.MSG_BIND;
            message.replyTo = messenger;
            //使用service的messenger發(fā)送activity中的Messenger
            try {
                mServiceMessenger.send(message);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            //解綁回調(diào)
        }
    };
@Override
    public IBinder onBind(Intent intent) {
        //創(chuàng)建一個(gè)Messenger對(duì)象
        Messenger messenger = new Messenger(mHandler);
        //返回Messenger的binder
        return messenger.getBinder();
    }
Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_INIT:
                    mSGINIT(msg);
                    break;
                case MSG_BIND:
                    //處理綁定的Messenger
                    mActivityMessenger = msg.replyTo;
                    break;
                case MSG_START:
                    mSGSTART(msg);
                    break;
                case MSG_STOP:
                    mSGSTOP(msg);
                    break;
            }
        }
    };

實(shí)現(xiàn)了activity和service的通信綁定,在點(diǎn)擊開(kāi)始或者暫停時(shí)就可以Messenger給service發(fā)送消息了;

private void doStart(FileInfo fileInfo) {
        //將開(kāi)始下載的文件id存儲(chǔ)在集合中
        if (fileIds.contains(fileInfo.id)) {
            //正在下載提示用戶 并返回
            Toast.makeText(this, "該文件正在下載中...", Toast.LENGTH_LONG).show();
            return;
        }
        //將文件id添加到集合中
        fileIds.add(fileInfo.id);
        Message message = new Message();
        message.what = DownLoadService.MSG_START;
        message.obj = fileInfo;
        try {
            mServiceMessenger.send(message);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        Log.e("doStart-->", "doStart");
    }
private void doStop(FileInfo fileInfo) {
        //暫停下載時(shí)將存儲(chǔ)的下載文件id移除
        for (int i = 0; i < fileIds.size(); i++) {
            Integer integer = fileIds.get(i);
            if (integer == fileInfo.id) {
                fileIds.remove(integer);
                break;
            }
        }
        Log.e("doStop-->", "doStop");
        Message message = new Message();
        message.what = DownLoadService.MSG_STOP;
        message.obj = fileInfo;
        try {
            mServiceMessenger.send(message);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

在開(kāi)始下載時(shí)需要將下載文件的id緩存的集合中,用于管理用戶多次點(diǎn)擊同一個(gè)正在下載的文件,在暫停下載或下載完成后在從集合中移除對(duì)應(yīng)的文件id,消息發(fā)送后,在Service中Handler的handerMessage()方法中根據(jù)msg.whate進(jìn)行處理。
開(kāi)始下載時(shí)還是和之前一樣,在子線程中獲取文件的大小,在本地創(chuàng)建文件夾,然后通過(guò)handler通知進(jìn)行下載,只是改成了利用線程池進(jìn)行線程的管理;

/**
     * 開(kāi)始下載
     *
     * @param msg
     */
    private void mSGSTART(Message msg) {
        FileInfo fileInfo = (FileInfo) msg.obj;
        Log.e(TAG, ACTION_START);
        //開(kāi)啟線程
        InitThread thread = new InitThread(fileInfo);
        DownLoadTask.sExecutorService.execute(thread);
    }

在下載的時(shí)候需要對(duì)多線程、多任務(wù)進(jìn)行管理,同時(shí)開(kāi)始時(shí)通過(guò)消息告訴activity去開(kāi)啟消息通知欄,顯示下載進(jìn)度;

/**
     * 初始化處理
     *
     * @param msg
     */
    private void mSGINIT(Message msg) {
        FileInfo fileInfo = (FileInfo) msg.obj;
        Log.e(TAG, MSG_INIT + "");
        //啟動(dòng)下載任務(wù)
        DownLoadTask task = new DownLoadTask(DownLoadService.this, fileInfo, 1, mActivityMessenger);
        task.downLoad();
        //把下載任務(wù)添加到集合中
        mTasks.put(fileInfo.id, task);
        //給Activity發(fā)送消息
        Message message = new Message();
        message.what = MSG_START;
        message.obj = fileInfo;
        try {
            mActivityMessenger.send(message);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

在activity的handler中就可以通知開(kāi)啟通知狀態(tài)欄,

/**
     * 開(kāi)始下載通知通知欄
     *
     * @param msg
     */
    private void mSGSTART(Message msg) {
        //顯示一個(gè)通知
        FileInfo info = (FileInfo) msg.obj;
        if (info != null) {
            mNotificationUtil.showNotification(info);
        }
    }
/**
 * 通知的工具類
 */
public class NotificationUtil {
    //實(shí)例化Notification通知管理類
    private NotificationManager mNotificationManager;
    //管理Notification的集合
    private Map<Integer, Notification.Builder> mNotification;
    private Context mContext;

    public NotificationUtil(Context context) {
        mContext = context;
        mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotification = new HashMap<>();
    }

    /**
     * 顯示notification
     */
    public void showNotification(FileInfo fileInfo) {
        //是否存在該文件下載通知
        if (!mNotification.containsKey(fileInfo.id)) {
            //android8.0 notification適配
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel("channel_id", "channel_name", NotificationManager.IMPORTANCE_DEFAULT);
                channel.canBypassDnd();//可否繞過(guò)請(qǐng)勿打擾模式
                channel.enableLights(true);//有新消息時(shí)手機(jī)有閃光
                channel.setLockscreenVisibility(Notification.VISIBILITY_SECRET);//鎖屏顯示通知
                channel.setLightColor(Color.argb(100, 100, 100, 100));//指定閃光時(shí)的燈光顏色
                channel.canShowBadge();//有新消息時(shí)桌面角標(biāo)顯示
                channel.enableVibration(true);//振動(dòng)
                AudioAttributes audioAttributes = channel.getAudioAttributes();//獲取系統(tǒng)響鈴
                channel.getGroup();//獲取通知渠道組
                channel.setBypassDnd(true);//設(shè)置可以繞過(guò)請(qǐng)勿打擾模式
                channel.setVibrationPattern(new long[]{100, 100, 200});//振動(dòng)模式
                channel.shouldShowLights();//是否會(huì)閃燈

                mNotificationManager.createNotificationChannel(channel);

            }
            //不存在就新增
            //創(chuàng)建通知的對(duì)象
            Notification.Builder notification;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                //android8.0 notification適配
                notification = new Notification.Builder(mContext)
                        .setChannelId("channel_id");
            } else {
                notification = new Notification.Builder(mContext);
            }
            //設(shè)置滾動(dòng)文字
            notification.setTicker(fileInfo.fileName + "開(kāi)始下載")
                    .setWhen(System.currentTimeMillis())//設(shè)置通知顯示的時(shí)間
                    .setSmallIcon(R.mipmap.ic_launcher_round)//設(shè)置圖標(biāo)
                    .setContentTitle(fileInfo.fileName)
                    .setContentText(fileInfo.fileName + "下載中...")
                    .setAutoCancel(true);//設(shè)置通知的特性  FLAG_AUTO_CANCEL點(diǎn)擊通知欄自動(dòng)消失

            //設(shè)置點(diǎn)擊通知欄的操作
            Intent intent = new Intent(mContext, MainActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
            notification.setContentIntent(pendingIntent);
            //發(fā)出通知廣播
            mNotificationManager.notify(fileInfo.id, notification.build());
            //把通知加到集合中
            mNotification.put(fileInfo.id, notification);
        }
    }

    /**
     * 取消通知
     *
     * @param id
     */
    public void cancleNotification(int id) {
        //取消通知
        mNotificationManager.cancel(id);
        //同時(shí)刪除集合中的通知
        mNotification.remove(id);
    }

    /**
     * 更新通知進(jìn)度
     *
     * @param id
     * @param progress
     */
    public void updateNotification(int id, int progress) {
        Notification.Builder notification = mNotification.get(id);
        if (notification != null) {
            //更新進(jìn)度條
            notification.setProgress(100, progress, false);
            //重新發(fā)送通知
            mNotificationManager.notify(id, notification.build());
        }
    }
}

消息通知欄是通過(guò)NotificationUtil工具類來(lái)管理的,調(diào)用showNotification()方法創(chuàng)建并顯示一個(gè)通知狀態(tài)欄,在進(jìn)度更新時(shí)調(diào)用updateNotification()方法,下載完成或者取消通知狀態(tài)欄調(diào)用cancleNotification()就可以了,NotificationUtil類中已經(jīng)對(duì)Notification做了8.0的適配處理,關(guān)于Notification的8.0適配網(wǎng)上很多資料,不過(guò)需要注意在調(diào)用setChannelId()時(shí)設(shè)置的id要和NotificationChannel創(chuàng)建時(shí)傳入的id一致;

NotificationChannel channel = new NotificationChannel("channel_id", "channel_name", NotificationManager.IMPORTANCE_DEFAULT);

在DownLoadTask中的downLoad()中還是要根據(jù)數(shù)據(jù)庫(kù)查詢的結(jié)果進(jìn)行下載,數(shù)據(jù)庫(kù)中如果有下載記錄,直接將查詢到的下載記錄傳入到下載線程中,如果沒(méi)有就需要新增一個(gè)下載任務(wù)實(shí)例,在新增的時(shí)候需要注意,要根據(jù)傳入的單個(gè)任務(wù)的下載線程個(gè)數(shù)來(lái)弄,要處理好每個(gè)線程的開(kāi)始下載位置和結(jié)束下載位置;

public void downLoad() {
        //讀取數(shù)據(jù)庫(kù)的線程信息
        List<ThreadInfo> threadInfos = dao.queryThread(mFileInfo.url);
        if (threadInfos.size() == 0) {
            //獲得每個(gè)線程下載的長(zhǎng)度 分線程下載,多個(gè)線程下載一個(gè)文件
            int length = mFileInfo.length / mThreadCount;
            for (int i = 0; i < mThreadCount; i++) {
                ThreadInfo threadInfo = new ThreadInfo();
                threadInfo.id = i;
                threadInfo.url = mFileInfo.url;
                threadInfo.thread_start = length * i;
                threadInfo.thread_end = (i + 1) * length - 1;
                threadInfo.finished = 0;
                if (i == mThreadCount - 1) {
                    //最后一個(gè)線程下載的結(jié)束位置
                    threadInfo.thread_end = mFileInfo.length;
                }
                //添加到線程集合信息
                threadInfos.add(threadInfo);
                //向數(shù)據(jù)庫(kù)中插入一條信息
                if (!dao.isExists(threadInfo.url, threadInfo.id)) {
                    dao.insertThread(threadInfo);
                }
            }
        }
        threadList = new ArrayList<>();
        //啟動(dòng)多個(gè)線程進(jìn)行下載
        for (ThreadInfo threadInfo : threadInfos) {
            DownLoadThread downLoadThread = new DownLoadThread(threadInfo);
            DownLoadTask.sExecutorService.execute(downLoadThread);
            threadList.add(downLoadThread);
        }
        //啟動(dòng)定時(shí)任務(wù)
        mTimer.schedule(timerTask, 1000, 1000);
    }

在開(kāi)始的同時(shí)開(kāi)啟一個(gè)Timer進(jìn)行輪詢;

TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            if (isPause) {
                //暫停時(shí)要將定時(shí)器清除掉
                cancelTimer();
            }
            //發(fā)送消息修改activity進(jìn)度
            Message message = new Message();
            message.what = DownLoadService.MSG_UPDATE;
            message.arg1 = mFinished * 100 / mFileInfo.length;
            message.arg2 = mFileInfo.id;
            Log.e("DownLoadService", mFinished + "");
            try {
                messenger.send(message);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    };

    /**
     * 清除定時(shí)器
     */
    private void cancelTimer(){
        //取消定時(shí)器
        timerTask.cancel();
        timerTask = null;
        mTimer.cancel();
        mTimer = null;
    }

在下載任務(wù)進(jìn)行的同時(shí)會(huì)每隔一段時(shí)間回調(diào)TimerTask中的run方法,通過(guò)Messenger向activity傳遞下載的進(jìn)度,在暫停下載是需要將Timer移除并置為null。
在DownLoadThread線程中下載完畢后做法和之前一樣,多了要將Timer移除并置為null;

/**
     * 下載線程
     */
    class DownLoadThread extends Thread {
        private ThreadInfo mThreadInfo;
        //線程是否執(zhí)行完畢
        public boolean isFinished = false;

        public DownLoadThread(ThreadInfo threadInfo) {
            mThreadInfo = threadInfo;
        }

        @Override
        public void run() {
            super.run();
            HttpURLConnection conn = null;
            RandomAccessFile raf = null;
            InputStream input = null;
            try {
                URL url = new URL(mThreadInfo.url);
                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(6000);
                conn.setRequestMethod("GET");
                //設(shè)置下載位置
                int start = mThreadInfo.thread_start + mThreadInfo.finished;
                conn.setRequestProperty("Range", "bytes=" + start + "-" + mThreadInfo.thread_end);
                //設(shè)置一個(gè)文件寫入位置
                File file = new File(DownLoadService.DOWNLOAD_PATH, mFileInfo.fileName);
                raf = new RandomAccessFile(file, "rwd");
                //設(shè)置文件寫入位置
                raf.seek(start);
                mFinished += mThreadInfo.finished;
                //開(kāi)始下載了
                if (conn.getResponseCode() == HttpURLConnection.HTTP_PARTIAL) {
                    //讀取數(shù)據(jù)
                    input = conn.getInputStream();
                    byte[] buffer = new byte[1024 * 4];
                    int len = -1;
                    while ((len = input.read(buffer)) != -1) {
                        //寫入文件
                        raf.write(buffer, 0, len);
                        //下載進(jìn)度發(fā)送廣播給activity
                        //累加整個(gè)文件的進(jìn)度
                        mFinished += len;
                        //累加每個(gè)線程下載的進(jìn)度
                        int currentFinished = mThreadInfo.finished;
                        mThreadInfo.finished = currentFinished + len;

                        //下載暫停是要把進(jìn)度保存在數(shù)據(jù)庫(kù)中
                        if (isPause) {
                            dao.updateThread(mThreadInfo.url, mThreadInfo.id, mThreadInfo.finished);
                            return;
                        }
                    }
                    //標(biāo)識(shí)線程執(zhí)行完畢
                    isFinished = true;
                    //檢查下載任務(wù)是否執(zhí)行完畢
                    checkAllThreadsFinished();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (conn != null) {
                        conn.disconnect();
                    }
                    if (raf != null) {
                        raf.close();
                    }
                    if (input != null) {
                        input.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
/**
     * 判斷是否所有線程執(zhí)行完畢
     */
    private synchronized void checkAllThreadsFinished() {
        boolean allFinished = true;
        //遍歷線程集合判斷線程是否執(zhí)行完畢
        for (DownLoadThread downLoadThread : threadList) {
            if (!downLoadThread.isFinished) {
                allFinished = false;
                break;
            }
        }
        if (allFinished) {
            cancelTimer();
            //發(fā)送消息告訴activity下載完畢
            Message message = new Message();
            message.what = DownLoadService.MSG_FINISHED;
            message.obj = mFileInfo;
            try {
                messenger.send(message);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            //刪除線程信息
            dao.deleteThread(mFileInfo.url);

        }
    }

在activity更新下載進(jìn)度時(shí)要根據(jù)對(duì)應(yīng)的文件id去更新進(jìn)度;

/**
     * 下載進(jìn)度更新
     *
     * @param msg
     */
    private void mSGUPDATE(Message msg) {
        int finished = msg.arg1;
        int id = msg.arg2;
        updataItem(id, finished);
        //更新通知進(jìn)度
        mNotificationUtil.updateNotification(id, finished);
    }

    /**
     * 下載完成后更新
     *
     * @param msg
     */
    private void mSGFINISHED(Message msg) {
        //更新進(jìn)度為0
        FileInfo fileInfo = (FileInfo) msg.obj;
        //下載完成后移除存儲(chǔ)的文件id
        for (int i = 0; i < fileIds.size(); i++) {
            Integer integer = fileIds.get(i);
            if (integer == fileInfo.id) {
                fileIds.remove(integer);
                break;
            }
        }
        if (fileInfo != null) {
            updataItem(fileInfo.id, fileInfo.length);
        }
        Log.e("fileInfo.length-->", fileInfo.length + "");
        Toast.makeText(MainActivity.this, fileInfo.fileName + "下載完畢", Toast.LENGTH_LONG).show();
        //下載完畢后取消通知
        mNotificationUtil.cancleNotification(fileInfo.id);
    }

    private void updataItem(int id, int finished) {
        for (int i = 0; i < lists.size(); i++) {
            FileInfo fileInfo = lists.get(i);
            if (fileInfo.id == id) {
                lists.remove(i);
                fileInfo.finished = finished;
                lists.add(i, fileInfo);
                break;
            }
        }
        adapter.updateProgress(lists);
    }

源碼地址

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容