服务的最佳实践------完整版的下载示例

本文详细介绍了如何在Android中实现下载服务,包括添加依赖、定义回调接口、创建DownloadTask和DownloadService,以及前端UI的实现和权限声明。通过这些步骤,确保下载任务能在后台持续运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如何实现安卓下载呢?接下来由我来告诉大家

首先我们需要在项目中添加依赖库,编辑app/build.gradle文件,在dependencies闭包中添加如下内容

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
**implementation'com.squareup.okhttp3:okhttp:3.4.1'**
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

接下来
定义一个回掉接口。新建一个 DownloadListene

package com.example.hejun.servicebestpractice;

public interface DownloadListener {

    void onProgress(int progress);
    void onSuccess();
    void onFailed();
    void onPaused();
    void onCanceled();

}

编写下载功能新建一个DownloadTask类

package com.example.hejun.servicebestpractice;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Environment;
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;

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_PAUSED = 2;
    public static final int TYPE_CANCELED = 3;

    private DownloadListener listener;
    private boolean isCanceled = false;
    private boolean isPaused = false;
    private int lastProgress;

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

    }
    @Override
    protected Integer doInBackground(String...parms){
        InputStream is = null;
        RandomAccessFile savedFile = null;
        File file = null;
        try{
            long  downloadLength = 0;//记录已经下载的文件长度
            String downloadUrl = parms[0];
            String fileName =downloadUrl.substring ( downloadUrl.lastIndexOf ( "/" ) );
            String directory = Environment.getExternalStoragePublicDirectory (
                    Environment.DIRECTORY_DOWNLOADS
            ).getPath ();
           file = new File ( directory +fileName );
            if (file.exists ()){
                downloadLength= file.length ();
            }
            long contentLength = getContentLength(downloadUrl);
            if (contentLength ==0){
                return TYPE_FAILED;
            }else if (contentLength == downloadLength){
                //已经下载字节和文件总字节相等,说明已经下载完成了
                return TYPE_SUCCESS;
            }
            OkHttpClient client = new OkHttpClient ();
            Request request = new Request.Builder ()
                    //断点下载
            .addHeader ( "RANGE","bytes="+downloadLength+"-" )
                    .url ( downloadUrl )
                    .build ();
            Response response = client.newCall ( request ).execute();
               if (response != null){
                   is = response.body ().byteStream ();
                   savedFile = new RandomAccessFile ( file,"rw" );
                   savedFile.
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值