安卓学习之下载

首先依赖okhttp

  1. 定义一个回调接口
public interface DownloadListener {

    void onProgress(int progress);//用于通知当前的下载进度

    void onSuccess();//用于通知下载成功事件

    void onFailed();//用于通知下载失败事件

    void onPaused();//用于通知下载暂停事件

    void onCanceled();//用于通知下载取消事件
}

  1. 编写下载功能

/**
 * //这里我们把第一个泛型参数设置成String,表示在执行AsyncTask的时候传入字符串参数给后台服务
 *   //第二个人泛型参数指定为Integer,表示使用整型数据来作为进度显示单位
 *   //第二个人泛型参数指定为Integer,则表示使用整型数据来反馈执行结果
 */
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... strings) {
        InputStream is=null;
        RandomAccessFile savefile=null;
        File file=null;
        try {
            long downloadedLength=0;
            String downloadUrl=strings[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);//调用getContentLength()来获取待下载文件的总长度

            if (contentLength==0){//如果文件长度为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){//如果获取的数据不为空 就使用java的文件流方式,不断从网上读取数据,不断写入到本地,一直到下载完成为止
                    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){//如果用户点击取消则返回TYPE_CANCELED
                            return TYPE_CANCELED;
                        }else if (isPaused){如果用户点击暂停则返回TYPE_PAUSED
                            return TYPE_PAUSED;
                        }else {//如果没有的话则实时计算当前的下载进度
                            total+=len;
                            savefile.write(b,0,len);
                            //计算已经下载的百分比
                            int progress=(int)((total+downloadedLength)*100/contentLength);
                            publishProgress(progress);//调用publishProgress()方法进行通知
                        }
                    }
                    response.body().close();
                    return  TYPE_SUCCESS;
                }
        } catch (Exception 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;

    }


    @Override
    protected void onProgressUpdate(Integer... values) {
        int progress=values[0];//从参数获取到当前的下载进度
        if (progress>lastProgress){//如果当前的下载进度大于上次的下载进度
            listener.onProgress(progress);//调用DownloadListener的onProgress()来通知下载进度更新
            lastProgress=progress;
        }
    }

    @Override
    protected void onPostExecute(Integer integer) {//根据参数中下载状态来进行回调
        switch (integer){
            case TYPE_SUCCESS:
                listener.onSuccess();
                break;
            case TYPE_FAILED:
                listener.onFailed();
                break;
            case TYPE_PAUSED:
                listener.onPaused();
                break;
            case TYPE_CANCELED:
                listener.onCanceled();
                break;
            default:
                break;
        }
    }
    public void pauseDownload(){
        isPaused=true;
    }

    public void cancelDownload(){
        isCanceled=true;
    }


    private long getContentLength(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;
    }

}
  1. 新建service

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("下载中..",progress));
        }

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

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


        }

        @Override
        public void onPaused() {//用于通知下载暂停事件
            downloadTask=null;
            Toast.makeText(DownloadService.this, "暂停下载", Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onCanceled() {//用于通知下载取消事件
            downloadTask=null;
            //下载取消时将前台服务通知关闭
            stopForeground(true);
            Toast.makeText(DownloadService.this, "取消下载", Toast.LENGTH_SHORT).show();

        }
    };
    DownloadBinder mybinder=new DownloadBinder();

    public DownloadService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mybinder;

    }
    class  DownloadBinder extends Binder{
        public void startDownload(String url){//开始下载
            if (downloadTask==null){
                DownloadUrl=url;
                downloadTask=new DownloadTask(listener);
                downloadTask.execute(DownloadUrl);
                startForeground(1,getNotification("下载中",0));
                Toast.makeText(DownloadService.this, "下载中", 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="我是文件名";
                    String directory= Environment.getExternalStorageState();
                    File file=new File(directory+fileName);
                    if (file.exists()){
                        file.delete();
                    }
                    getNotificationManager().cancel(1);
                    Toast.makeText(DownloadService.this, "取消下载", Toast.LENGTH_SHORT).show();
                }
            }
        }

    }

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

    private Notification getNotification(String title,int progress) {
        String id = "my_channel_033";
        String name = "我是渠道名33";
        Notification notification = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel mchannel =
                    new NotificationChannel(id, name, NotificationManager.IMPORTANCE_HIGH);
            getNotificationManager().createNotificationChannel(mchannel);
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, id);

        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);

        builder.setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(title)
                .setContentIntent(pi);//跳转
        if (progress>0){
            //当progress大于等于0时才需要显示下载进度
            builder.setContentText(progress+"%");
            builder.setProgress(100,progress,false);
        }

        return builder.build();
    }
}
  1. 好了,后端的工作完成了,接下来编写前端
<?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="wrap_content"
        android:layout_height="wrap_content"
        android:text="开始"/>

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

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

</LinearLayout>

  1. Mian方法当中

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button start;
    private Button pause;
    private Button cancel;

    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);

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

        }
        }

    @Override
    public void onClick(View v) {
        if (downloadBinder==null){
            return;
        }
        switch (v.getId()){
            case R.id.start:
                String url="这里是下载地址";
                downloadBinder.startDownload(url);
                break;
            case R.id.pause:
                downloadBinder.pauseDownload();
                break;
            case R.id.cancel:
                downloadBinder.cancelDownload();
                break;
            default:
                break;

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 222:
                if (grantResults.length>0&&grantResults[0]!=PackageManager.PERMISSION_GRANTED){

                    Toast.makeText(this, "你取消了授权", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }

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

好了,运行 完美成功在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
资源包主要包含以下内容: ASP项目源码:每个资源包中都包含完整的ASP项目源码,这些源码采用了经典的ASP技术开发,结构清晰、注释详细,帮助用户轻松理解整个项目的逻辑和实现方式。通过这些源码,用户可以学习到ASP的基本语法、服务器端脚本编写方法、数据库操作、用户权限管理等关键技术。 数据库设计文件:为了方便用户更好地理解系统的后台逻辑,每个项目中都附带了完整的数据库设计文件。这些文件通常包括数据库结构图、数据表设计文档,以及示例数据SQL脚本。用户可以通过这些文件快速搭建项目所需的数据库环境,并了解各个数据表之间的关系和作用。 详细的开发文档:每个资源包都附有详细的开发文档,文档内容包括项目背景介绍、功能模块说明、系统流程图、用户界面设计以及关键代码解析等。这些文档为用户提供了深入的学习材料,使得即便是从零开始的开发者也能逐步掌握项目开发的全过程。 项目演示与使用指南:为帮助用户更好地理解和使用这些ASP项目,每个资源包中都包含项目的演示文件和使用指南。演示文件通常以视频或图文形式展示项目的主要功能和操作流程,使用指南则详细说明了如何配置开发环境、部署项目以及常见问题的解决方法。 毕业设计参考:对于正在准备毕业设计的学生来说,这些资源包是绝佳的参考材料。每个项目不仅功能完善、结构清晰,还符合常见的毕业设计要求和标准。通过这些项目,学生可以学习到如何从零开始构建一个完整的Web系统,并积累丰富的项目经验。
资源包主要包含以下内容: ASP项目源码:每个资源包中都包含完整的ASP项目源码,这些源码采用了经典的ASP技术开发,结构清晰、注释详细,帮助用户轻松理解整个项目的逻辑和实现方式。通过这些源码,用户可以学习到ASP的基本语法、服务器端脚本编写方法、数据库操作、用户权限管理等关键技术。 数据库设计文件:为了方便用户更好地理解系统的后台逻辑,每个项目中都附带了完整的数据库设计文件。这些文件通常包括数据库结构图、数据表设计文档,以及示例数据SQL脚本。用户可以通过这些文件快速搭建项目所需的数据库环境,并了解各个数据表之间的关系和作用。 详细的开发文档:每个资源包都附有详细的开发文档,文档内容包括项目背景介绍、功能模块说明、系统流程图、用户界面设计以及关键代码解析等。这些文档为用户提供了深入的学习材料,使得即便是从零开始的开发者也能逐步掌握项目开发的全过程。 项目演示与使用指南:为帮助用户更好地理解和使用这些ASP项目,每个资源包中都包含项目的演示文件和使用指南。演示文件通常以视频或图文形式展示项目的主要功能和操作流程,使用指南则详细说明了如何配置开发环境、部署项目以及常见问题的解决方法。 毕业设计参考:对于正在准备毕业设计的学生来说,这些资源包是绝佳的参考材料。每个项目不仅功能完善、结构清晰,还符合常见的毕业设计要求和标准。通过这些项目,学生可以学习到如何从零开始构建一个完整的Web系统,并积累丰富的项目经验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值