说说如何使用 Android 服务下载文件(支持断点续传)

1 添加网络库

在 build.gradle 中添加 okhttp3 库:

compile 'com.squareup.okhttp3:okhttp:3.10.0'

2 定义监听器

定义下载监听器,监听下载过程中的各种情况:

public interface DownloadListener {

    /**
     * 当前下载进度
     *
     * @param progress 下载进度
     */
    void onProgress(int progress);

    /**
     * 下载成功
     */
    void onSuccess();

    /**
     * 下载失败
     */
    void onFailed();

    /**
     * 暂停下载
     */
    void onPaused();

    /**
     * 取消下载
     */
    void onCanceled();
}

3 定义异步下载任务

public class DownloadTask extends AsyncTask<String, Integer, DownloadTask.DownloadResult> {


    private static final String TAG = "DownloadTask";

    /**
     * 下载结果
     */
    public enum DownloadResult {
        //下载成功
        SUCCESS,
        //下载失败
        FAILED,
        //下载被暂停
        PAUSED,
        //下载被取消
        CANCELED
    }

    //是否取消下载
    private boolean isCanceled = false;

    //是否暂停下载
    private boolean isPaused = false;

    //上一次的下载进度
    private int lastProgress;


    private DownloadListener listener;


    public DownloadTask(DownloadListener listener) {
        this.listener = listener;
    }

    /**
     * 下载
     *
     * @param params
     * @return
     */
    @Override
    protected DownloadResult doInBackground(String... params) {
        InputStream inputStream = null;
        RandomAccessFile downloadedFile = null;
        File file = null;

        try {
            long downloadedLength = 0;//文件已下载的大小
            String url = params[0];//获取下载地址
            String fileName = url.substring(url.lastIndexOf("/"));
            //指定 SD 卡的 Download 目录
            String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
            file = new File(directory + fileName);

            if (file.exists()) {//文件已存在,则读取已下载的文件字节数(用于断点续传)
                downloadedLength = file.length();
            }

            long contentLength = getContentLength(url);//获取待下载文件的总长度
            Log.d(TAG, "doInBackground: 待下载文件的总长度:" + contentLength);
            Log.d(TAG, "doInBackground: 已下载文件的总长度:" + downloadedLength);
            if (contentLength == 0) {//下载失败
                return DownloadResult.FAILED;
            } else if (contentLength == downloadedLength) {//下载成功
                return DownloadResult.SUCCESS;
            }

            OkHttpClient client = buildHttpClient();
            Request request = new Request.Builder()
                    //指定从那个字节开始下载,即【断点下载】
                    .addHeader("RANGE", "bytes=" + downloadedLength + "-")
                    .url(url)
                    .build();
            Response response = client.newCall(request).execute();
            if (response != null) {
                inputStream = response.body().byteStream();
                downloadedFile = new RandomAccessFile(file, "rw");
                downloadedFile.seek(downloadedLength);//跳转到未下载的字节节点
                byte[] bytes = new byte[1024];
                int total = 0;//下载的总字节数
                int readLength;//读取的字节数
                while ((readLength = inputStream.read(bytes)) != -1) {
                    //在下载的过程中,判断下载是否被取消或者被暂停
                    if (isCanceled) {//取消
                        return DownloadResult.CANCELED;
                    } else if (isPaused) {//暂停
                        return DownloadResult.PAUSED;
                    } else {
                        total += readLength;
                        downloadedFile.write(bytes, 0, readLength);
                        //计算已下载的进度(单位:百分比)
                        int progress = (int) ((total + downloadedLength) * 100 / contentLength);
                        //发布下载进度
                        publishProgress(progress);
                    }
                }
                response.body().close();
                return DownloadResult.SUCCESS;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (downloadedFile != null) {
                    downloadedFile.close();
                }
                if (isCanceled && file != null) {
                    file.delete();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return DownloadResult.FAILED;
    }

    @NonNull
    private OkHttpClient buildHttpClient() {
        return new OkHttpClient.Builder().retryOnConnectionFailure(true).connectTimeout(30, TimeUnit.SECONDS).build();
    }

    /**
     * 更新当前的下载进度
     *
     * @param values
     */
    @Override
    protected void onProgressUpdate(Integer... values) {
        int progress = values[0];
        if (progress > lastProgress) {
            listener.onProgress(progress);
            lastProgress = progress;
        }
    }

    /**
     * 根据下载结果调用相应的回调方法
     *
     * @param result
     */
    @Override
    protected void onPostExecute(DownloadResult result) {
        switch (result) {
            case SUCCESS:
                listener.onSuccess();
                break;
            case FAILED:
                listener.onFailed();
                break;
            case PAUSED:
                listener.onPaused();
                break;
            case CANCELED:
                listener.onCanceled();
                break;
            default:
                break;
        }
    }

    /**
     * 暂停下载
     */
    public void pause() {
        isPaused = true;
    }

    /**
     * 取消下载
     */
    public void cancel() {
        isCanceled = true;
    }


    /**
     * 获取待下载文件的总长度
     *
     * @param url 下载文件地址
     * @return
     */
    private long getContentLength(String url) throws IOException {
        Log.d(TAG, "getContentLength:url:" + url);
        OkHttpClient client = buildHttpClient();
        Request request = new Request.Builder().url(url).build();
        Response response = client.newCall(request).execute();
        if (response != null && response.isSuccessful()) {
            long contentLength = response.body().contentLength();
            response.close();
            return contentLength;
        } else {
            return 0;
        }
    }


}

DownloadTask 类做了这些工作:

1、继承 AsyncTask 类并传入三个参数:

extends AsyncTask<String, Integer, DownloadTask.DownloadResult>
参数 说明
String 表示传递到后台服务的参数类型,这里参数指的是文件下载 URL 地址。
Integer 表示使用整型数据作为下载进度的显示单位。
DownloadResult 使用 DownloadResult 枚举类型来定义下载结果。

2、定义了枚举类型的下载结果。
3、重写了这些方法:

  • doInBackground - 执行下载操作。
  • onProgressUpdate - 更新当前的下载进度。
  • onPostExecute - 根据下载结果调用相应的回调方法。

在 doInBackground 中,根据已下载的文件字节总数与要下载的字节总数做比较,让程序直接跳过已下载的字节,所以支持断点续传哦O(∩_∩)O哈哈~

4 定义下载服务

public class DownloadService extends Service {

    private DownloadTask task;

    private String url;

    public static final int NOTIFICATION_ID = 1;


    private DownloadListener listener = new DownloadListener() {
        @Override
        public void onProgress(int progress) {
            getNotificationManager().notify(NOTIFICATION_ID, buildNotification("下载中……", progress));
        }

        @Override
        public void onSuccess() {
            task = null;

            //关闭前台服务
            stopForeground(true);

            //通知下载成功
            getNotificationManager().notify(NOTIFICATION_ID, buildNotification("下载成功", -1));
            Toast.makeText(DownloadService.this, "下载成功", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailed() {
            task = null;

            //关闭前台服务
            stopForeground(true);

            //通知下载失败
            getNotificationManager().notify(NOTIFICATION_ID, buildNotification("下载失败", -1));
            Toast.makeText(DownloadService.this, "下载失败", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onPaused() {
            task = null;
            Toast.makeText(DownloadService.this, "暂停下载", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCanceled() {
            task = null;

            //关闭前台服务
            stopForeground(true);

            //通知下载取消
            Toast.makeText(DownloadService.this, "取消下载", Toast.LENGTH_SHORT).show();
        }
    };


    private NotificationManager getNotificationManager() {
        return (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }


    /**
     * 构建【下载进度】通知
     *
     * @param title    通知标题
     * @param progress 下载进度
     */
    private Notification buildNotification(String title, int progress) {
        Intent intent = new Intent(this, MainActivity.class);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        builder.setContentTitle(title);
        int requestCode = 0;
        int flags = PendingIntent.FLAG_UPDATE_CURRENT;
        builder.setContentIntent(PendingIntent.getActivity(this, requestCode, intent, flags));
        if (progress > 0) {
            builder.setContentText(progress + "%");
            builder.setProgress(100, progress, false);
        }
        return builder.build();
    }

    public DownloadService() {
    }


    @Override
    public IBinder onBind(Intent intent) {
        return new DownloadBinder();
    }

    /**
     * 通过 Binder 让服务与活动之间实现通信
     */
    protected class DownloadBinder extends Binder {
        /**
         * 开始下载
         *
         * @param url
         */
        public void start(String url) {
            if (task == null) {
                DownloadService.this.url = url;
                task = new DownloadTask(listener);
                task.execute(url);
                startForeground(NOTIFICATION_ID, buildNotification("开始下载……", 0));
                Toast.makeText(DownloadService.this, "开始下载……", Toast.LENGTH_SHORT).show();
            }
        }

        /**
         * 暂停下载
         */
        public void pause() {
            if (task != null) {
                task.pause();
            }
        }

        /**
         * 取消下载
         */
        public void cancel() {
            if (task != null) {
                task.cancel();
                return;
            }

            if (url == null) {
                return;
            }

            //删除已下载文件
            String fileName = url.substring(url.lastIndexOf("/"));
            String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
            File file = new File(directory + fileName);
            if (file.exists()) {
                file.delete();
            }

            //关闭通知
            getNotificationManager().cancel(NOTIFICATION_ID);
            stopForeground(true);
            Toast.makeText(DownloadService.this, "被取消", Toast.LENGTH_SHORT).show();

        }
    }
}

这个大类做了以下工作:

  1. 通过匿名类创建了 DownloadListener 实例。
  2. 构建【下载进度】通知。
  3. 通过 Binder 让服务与活动之间实现通信。

这里的 setProgress 定义如下:

public Builder setProgress(int max, int progress, boolean indeterminate)
参数 说明
max 最大进度。
progress 当前进度。
indeterminate 是否使用模糊进度条。

5 定义控制按钮

布局文件:

<?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/start"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="开始下载" />

    <Button
        android:id="@+id/pause"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="暂停下载" />

    <Button
        android:id="@+id/cancel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="取消下载" />


</LinearLayout>

这里,我们定义了【开始】、【暂停】与【取消】按钮。

6 定义活动类

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    public static final int REQUEST_CODE = 1;


    private DownloadService.DownloadBinder binder;

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

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

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

        findViewById(R.id.start).setOnClickListener(this);
        findViewById(R.id.pause).setOnClickListener(this);
        findViewById(R.id.cancel).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},
                    REQUEST_CODE);
        }
    }

    @Override
    public void onClick(View v) {
        if (binder == null) {
            return;
        }

        switch (v.getId()) {
            case R.id.start:
                String url = "http://mirrors.shu.edu.cn/apache/maven/maven-3/3.5.4/binaries/apache-maven-3.5.4-bin.zip";
                binder.start(url);
                break;
            case R.id.pause:
                binder.pause();
                break;
            case R.id.cancel:
                binder.cancel();
                break;
            default:
                break;
        }
    }

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

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //解绑服务
        unbindService(connection);
    }
}

活动类中做了这些事:

  1. 建立与服务的绑定关系。
  2. 为按钮定义点击事件。
  3. 申请权限。

注意: 在 onDestroy() 中要记得解绑服务哦。

在代码中,我们把 Maven 作为下载演示路径。O(∩_∩)O哈哈~

7 声明权限与服务

AndroidManifest.xml

<!--网络权限-->
<uses-permission android:name="android.permission.INTERNET"/>

<!--访问 SD 卡权限-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    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>

    <service
        android:name=".DownloadService"
        android:enabled="true"
        android:exported="true"></service>
</application>

8 运行

第一次运行会弹出权限申请:

点击 ALLOW 后,就可以点击相应的按钮进行下载控制啦。点击【开始】按钮后,可以在通知中看到下载进度:


一个支持断点续传的 Android 下载服务就完成啦,是不是很有成就感呀O(∩_∩)O哈哈~

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

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,104评论 25 707
  • 下雨的时候生意很淡,来的人很少,她与她一起当迎宾的那个女子,站在门口。没有太多的话。青红记得那个女子有个手机,总是...
    无戒阅读 1,861评论 6 18
  • 2018.6.25.星期一,雨 老公很早就上班去了,六点多点就听见大宝在屋里早读,我醒了也不想起来,感觉浑身像散了...
    三年级四班李雨轩妈妈阅读 132评论 0 1
  • 老妈身体不舒服,所以今天带老人家去医院做检查,虽然是正月里,但是医院里人一点也不少,排队挂号看病的人很多,医生给老...
    Tracy_zhang阅读 159评论 0 0