service+okhttp实现断点续传下载

来源:互联网 发布:拉勾网简历被转发 知乎 编辑:程序博客网 时间:2024/06/07 01:36

DownloadListener

public interface DownloadListener {    void onProgress(int progress);    void onSuccess();    void onFailed();    void onPause();    void onCanceled();}

DownloadTask

/** * 第一个参数表示后台任务 * 第二个为进度 * 第三个为执行结果 */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 isPauesd = false;    private int lastProgress;    public DownloadTask(DownloadListener listener){        this.listener = listener;    }    @Override    protected Integer doInBackground(String... params) {        InputStream is = null;        RandomAccessFile savedFile = null;        File file = null;        try{            long downloadedLength = 0; //记录已下载的文件长度            String downloadUrl = params[0];            String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"));            //sd卡的download目录            String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();            file = new File(directory + fileName);            if(file.exists()){                downloadedLength = file.length();            }            long contentLength = getContnetLength(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();            Response response = client.newCall(request).execute();            if(response != null){                is = response.body().byteStream();                savedFile = new RandomAccessFile(file, "rw");                savedFile.seek(downloadedLength);//跳过已下载的字节                byte[] b = new byte[1024];                int total = 0;                int len;                while((len = is.read(b)) != -1){                    if(isCancelled()){                        return TYPE_CANCELED;                    } else if(isPauesd){                        return TYPE_PAUSED;                    } else {                        total += len;                        savedFile.write(b, 0, len);                        //计算已下载的百分比                        int progress = (int) ((total + downloadedLength) * 100 / contentLength);                        publishProgress(progress);                    }                }                response.body().close();                return TYPE_SUCCESS;            }        } catch (Exception e){            e.printStackTrace();        } finally {            try {                if (is != null) {                    is.close();                }if (savedFile != null) {                    savedFile.close();                }                if (isCancelled() && file != null) {                    file.delete();                }            }catch (Exception e){                e.printStackTrace();            }        }        return TYPE_FAILED;    }    private long getContnetLength(String downloadUrl) throws IOException {        OkHttpClient client = new OkHttpClient();        Request request = new Request.Builder()                .url(downloadUrl)                .build();        Response response = client.newCall(request).execute();        if(response != null && response.isSuccessful()){            long contentLength = response.body().contentLength();            response.close();            return  contentLength;        }        return 0;    }    @Override    protected void onProgressUpdate(Integer... values) {        int progress = values[0];        if (progress > lastProgress) {            listener.onProgress(progress);            lastProgress = progress;        }    }    @Override    protected void onPostExecute(Integer status) {        switch (status) {            case TYPE_SUCCESS:                listener.onSuccess();                break;            case TYPE_FAILED:                listener.onFailed();                break;            case TYPE_PAUSED:                listener.onPause();                break;            case TYPE_CANCELED:                listener.onCanceled();            default:                break;        }    }    public void pauseDownload() {        isPauesd = true;    }    public void cancelDownload() {        isPauesd = true;    }}

DownloadService

public class DownloadService extends Service {    private DownloadTask downloadTask;    private String downloadUrl;    private DownloadListener listener = new DownloadListener() {        @Override        public void onProgress(int progress) {            getNotificationManager().notify(1, getNotification("Downloading...", progress));        }        @Override        public void onSuccess() {            downloadTask = null;            //下载成功将前台服务通知关闭,并创建一个下载成功的通知            stopForeground(true);            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();        }    };    private Notification getNotification(String title, int progress) {        Intent intent = new Intent(this, MainActivity.class);        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) {            //当进度大于或等于0时才需要显示下载进度            builder.setContentText(progress + "%");            builder.setProgress(100, progress, false);        }        return builder.build();    }    private NotificationManager getNotificationManager() {        return (NotificationManager) getSystemService(NOTIFICATION_SERVICE);    }    public DownloadService() {    }    @Override    public IBinder onBind(Intent intent) {        return mBinder;    }    private DownloadBinder mBinder = new DownloadBinder();    class DownloadBinder extends Binder{        public void startDownload (String url) {            if (downloadTask == null) {                downloadUrl = url;                downloadTask = new DownloadTask(listener);                downloadTask.execute(downloadUrl);                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();                }            }        }    }}

MainActivity

public class MainActivity extends AppCompatActivity implements View.OnClickListener {    private DownloadService.DownloadBinder downloadBinder;    private ServiceConnection connection = new ServiceConnection() {        @Override        public void onServiceConnected(ComponentName name, IBinder service) {            downloadBinder = (DownloadService.DownloadBinder) service;        }        @Override        public void onServiceDisconnected(ComponentName name) {        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        Button btnStart = (Button) findViewById(R.id.btnStart);        Button btnPause = (Button) findViewById(R.id.btnPause);        Button btnCancel = (Button) findViewById(R.id.btnCancel);        btnCancel.setOnClickListener(this);        btnPause.setOnClickListener(this);        btnStart.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.btnStart:                String url = "https://raw.githubusercontent.com/guolindev/eclipse/master/eclipse-inst-win64.exe";                downloadBinder.startDownload(url);                break;            case R.id.btnPause:                downloadBinder.pauseDownload();                break;            case R.id.btnCancel:                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);    }}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.lzz.servicebestpractice">    <uses-permission android:name="android.permission.INTERNET"/>    <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></manifest>

源码下载

原创粉丝点击