Android之完整版的下载示例

终于写完了,但是感觉有时候不是太理解,书上有的说的很模糊,有时候甚至一带而过,不过这样也挺好的,能够锻炼一下自己的自学能力,对代码的理解能力。如果每段代码有大量的注释也不是很好,理解它的核心内容就可以了。

下面看看效果图:
这里写图片描述
这里写图片描述
这里写图片描述

DownloadTask.java

package com.example.lenovo.servicebestprectice;

import android.app.DownloadManager;
import android.os.AsyncTask;
import android.os.Environment;
import android.webkit.DownloadListener;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Lenovo on 2017/9/17.
 */

public class DownloadTask extends AsyncTask<String,Integer,Integer>{
    
    
    public static final int TYPE_SUCCESS = 0;
    public static final int TYPE_FAILED = 1;
    public static final int TYPE_PAUSE = 2;
    public static final int TYPE_CANCELED = 3;

    private DownLoadListener listener;
    private boolean isCanceled = false;
    private boolean isPause = false;
    private int lastProgress;
    public DownloadTask(DownLoadListener listener){
    
    
        this.listener = listener;
    }

    /*doInBackground方法 将在onPreExecute 方法执行后马上执行,该方法运行在后台线程中。
    * 这里将主要负责执行那些很耗时的后台处理工作。可以调用 publishProgress方法来更新实时的任务进度。
    * 该方法是抽象方法,子类必须实现。
    * */

    @Override
    protected Integer doInBackground(String... params) {
    
    
        InputStream is = null;
        RandomAccessFile saveFile = null;
        File file = null;

        long downloadedLength = 0;//记录已下载的文件长度
        String downloadUrl = params[0];
        String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"));
        String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
        file = new File(directory + fileName);
        if (file.exists()){
    
    
            downloadedLength = file.length();
        }
        long contentLength = getContentLength(downloadUrl);
        if (contentLength==0){
    
    
            return TYPE_FAILED;
        }else if (contentLength == downloadedLength){
    
    
            return TYPE_SUCCESS;
        }
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                //断点下载,指定从哪个字节下载
                .addHeader("RANGE","bytes = "+downloadedLength+"-")
                .url(downloadUrl)
                .build();
        try {
    
    
            Response response = client.newCall(request).execute();
            if (response !=  null){
    
    
                is = response.body().byteStream();
                saveFile = new RandomAccessFile(file,"rw");
                saveFile.seek(downloadedLength);//跳过已下载的字节
                byte[] b = new byte[1024];
                int total = 0;
                int len ;
                while ((len = is.read(b))!=-1){
    
    
                    if (isCanceled){
    
    
                        return TYPE_CANCELED;
                    }else if (isPause){
    
    
                        return TYPE_PAUSE;
                    }else {
    
    
                        total+=len;
                        saveFile.write(b,0,len);
                        //计算已下载的百分比
                        int progress = (int) ((total+downloadedLength)*100/contentLength);
                        publishProgress(progress);
                    }
                }
                response.body().close();
                return TYPE_SUCCESS;
            }
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }finally {
    
    
            try {
    
    
                if (is != null){
    
    
                        is.close();
                }
                if (saveFile!=null){
    
    
                    saveFile.close();
                }
                if (isCanceled && file!=null){
    
    
                    file.delete();
                }
            }catch (Exception e){
    
    
                e.printStackTrace();
            }
        }
        return TYPE_FAILED;
    }

    /*
    * onProgressUpdate(Progress…),在publishProgress方法被调用后,
    * UI 线程将调用这个方法从而在界面上展示任务的进展情况,例如通过一个进度条进行展示。
    * */
    @Override
    protected void onProgressUpdate(Integer... values) {
    
    
        int progress = values[0];
        if (progress > lastProgress){
    
    
            listener.onProgress(progress);
            lastProgress = progress;
        }
    }

    /*
    * 在doInBackground 执行完成后,onPostExecute 方法将被UI 线程调用,
    * 后台的计算结果将通过该方法传递到UI 线程,并且在界面上展示给用户.
    * */

    @Override
    protected void onPostExecute(Integer status) {
    
    
        switch (status){
    
    
            case TYPE_SUCCESS:
                listener.onSuccess();
                break;
            case TYPE_FAILED:
                listener.onFailed();
                break;
            case TYPE_PAUSE:
                listener.onPause();
                break;
            case TYPE_CANCELED:
                listener.onCanceled();
                break;
            default:
                break;
        }
    }
    public void pauseDownload(){
    
    
        isPause = true;
    }
    public void cancelDownload(){
    
    
        isCanceled = true;
    }

    private long getContentLength(String downloadUrl){
    
    
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(downloadUrl)
                .build();
        try {
    
    
            Response response = client.newCall(request).execute();
            if (response!=null && response.isSuccessful()){
    
    
                long contentlength = response.body().contentLength();
                response.close();
                return contentlength;
            }
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
        return 0;
    }
}

DownloadService.java

package com.example.lenovo.servicebestprectice;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;
import android.support.v7.app.NotificationCompat;
import android.webkit.DownloadListener;
import android.widget.Toast;

import java.io.File;

public class DownloadService extends Service {
    
    

    private DownloadTask downloadTask ;

    private String downloadUrl;

    private DownLoadListener listener = new DownLoadListener() {
    
    
        @Override
        public void onProgress(int profress) {
    
    
            getNotificationManager().notify(1,getNotification("Downloading...",profress));
        }

        @Override
        public void onSuccess() {
    
    
            downloadTask = null;
            //下载成功前将前台服务通知关闭,并创建一个下载成功的通知
            stopForeground(true);
            //触发getNotification通知
            getNotificationManager().notify(1,getNotification("Download success",-1));
            Toast.makeText(DownloadService.this, "Download Success", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailed() {
    
    
            downloadTask = null;
            //下载失败前将前台服务通知关闭,并创建一个下载失败的通知
            stopForeground(true);
            getNotificationManager().notify(1,getNotification("Download Failed",-1));
            Toast.makeText(DownloadService.this, "Download Failed", Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onPause() {
    
    
            downloadTask = null;
            Toast.makeText(DownloadService.this, "paused", Toast.LENGTH_SHORT).show();
        }


        @Override
        public void onCanceled() {
    
    
            downloadTask = null;
            stopForeground(true);
            Toast.makeText(DownloadService.this, "Canceled", Toast.LENGTH_SHORT).show();
        }
    };

    public DownloadService() {
    
    
    }
    private DownloadBinder mBinder = new DownloadBinder();

    @Override
    public IBinder onBind(Intent intent) {
    
    
       return mBinder;
    }
    class DownloadBinder extends Binder{
    
    
        public void startDownload(String url){
    
    
            if (downloadTask == null){
    
    
                downloadUrl = url;
                downloadTask = new DownloadTask(listener);
                downloadTask.execute(downloadUrl);
                //为了让下载服务成为一个前台服务,我们还调用了startForeground()
                startForeground(1,getNotification("Downloading...",0));
                Toast.makeText(DownloadService.this, "Downloading...", Toast.LENGTH_SHORT).show();
            }
        }
        public void pauseDownload(){
    
    
            if (downloadTask!=null){
    
    
                downloadTask.pauseDownload();
            }
        }
        public void cancelDownload(){
    
    
            if (downloadTask!=null){
    
    
                downloadTask.cancelDownload();
            }else {
    
    
                if (downloadUrl!=null){
    
    
                    //取消下载时需要将文件删除,并将通知关闭
                    String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"));
                    String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
                    File file = new File(directory + fileName);
                    if (file.exists()){
    
    
                        file.delete();
                    }
                    getNotificationManager().cancel(1);
                    stopForeground(true);
                    Toast.makeText(DownloadService.this, "Canceled", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    private NotificationManager getNotificationManager(){
    
    
        //获取通知管理器
        return (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }
    //用于显示下载进度的通知
    private Notification getNotification(String title,int progress){
    
    
        Intent intent = new Intent(this,MainActivity.class);
        // 创建一个PendingIntent,和Intent类似,不同的是由于不是马上调用,
        // 需要在下拉状态条出发的activity,所以采用的是PendingIntent,
        // 即点击Notification跳转启动到哪个Activity
        PendingIntent pi = PendingIntent.getActivity(this,0,intent,0);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher));
        builder.setContentIntent(pi);
        builder.setContentTitle(title);
        if (progress > 0){
    
    
            builder.setContentText(progress+"%");
            //第一个参数通知最大参数,
            //第二个参数传入通知的当前进度
            //第三个参数表示是否使用模糊的进度条
            builder.setProgress(100,progress,false);
        }
        return builder.build();
    }
}

MainActivity.java

package com.example.lenovo.servicebestprectice;

import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    
    

    private DownloadService.DownloadBinder downloadBinder;
    private Button mBtnstartDownload,mBtnPauseDownload,mBtnCanceDownload;

    private ServiceConnection connection = new ServiceConnection() {
    
    
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
    
    
            downloadBinder = (DownloadService.DownloadBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
    
    

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBtnstartDownload = (Button) findViewById(R.id.btn_start_download);
        mBtnPauseDownload = (Button) findViewById(R.id.btn_pause_download);
        mBtnCanceDownload = (Button) findViewById(R.id.btn_cancel_download);
        mBtnstartDownload.setOnClickListener(this);
        mBtnPauseDownload.setOnClickListener(this);
        mBtnCanceDownload.setOnClickListener(this);
        Intent intent = new Intent(this,DownloadService.class);
        startService(intent);//启动服务
        bindService(intent,connection,BIND_AUTO_CREATE);//绑定服务
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
    
    
            ActivityCompat.requestPermissions(MainActivity.this,new String[]{
    
    Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
        }
    }

    @Override
    public void onClick(View v) {
    
    
        if (downloadBinder == null){
    
    
            return;
        }
        switch (v.getId()){
    
    
            case R.id.btn_start_download:
                String url = "https://raw.githubusercontent.com/guolindev/eclipse/master/eclipse-inst-win64.exe";
                downloadBinder.startDownload(url);
                break;
            case R.id.btn_pause_download:
                downloadBinder.pauseDownload();
                break;
            case R.id.btn_cancel_download:
                downloadBinder.cancelDownload();
                break;
            default:
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    
    
        switch (requestCode){
    
    
            case 1:
                if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED){
    
    
                    Toast.makeText(this, "拒绝权限无法使用程序", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
        }
    }

    @Override
    protected void onDestroy() {
    
    
        super.onDestroy();
        unbindService(connection);
    }
}

DownLoadListener.java

package com.example.lenovo.servicebestprectice;

/**
 * Created by Lenovo on 2017/9/17.
 */

public interface DownLoadListener {
    
    
    void onProgress(int profress);
    void onSuccess();
    void onFailed();
    void onPause();
    void onCanceled();
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >
    <Button
        android:id="@+id/btn_start_download"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Start Download"
        android:textAllCaps="false"
        />
    <Button
        android:id="@+id/btn_pause_download"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Pause Download"
        android:textAllCaps="false"
        />
    <Button
        android:id="@+id/btn_cancel_download"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Cancel Download"
        android:textAllCaps="false"
        />

</LinearLayout>

猜你喜欢

转载自blog.csdn.net/i_nclude/article/details/78023159