xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" > <ProgressBar
android:id="@+id/pb_progress"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp" /> <TextView
android:id="@+id/tv_result"
android:layout_width="match_parent"
android:layout_height="wrap_content" /> <Button
android:id="@+id/btn_start_download"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="下载" /> </LinearLayout>

java:

 import com.yolanda.nohttp.Headers;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.download.DownloadListener;
import com.yolanda.nohttp.download.DownloadRequest;
import com.yolanda.nohttp.error.ArgumentError;
import com.yolanda.nohttp.error.ClientError;
import com.yolanda.nohttp.error.NetworkError;
import com.yolanda.nohttp.error.ServerError;
import com.yolanda.nohttp.error.StorageReadWriteError;
import com.yolanda.nohttp.error.StorageSpaceNotEnoughError;
import com.yolanda.nohttp.error.TimeoutError;
import com.yolanda.nohttp.error.URLError;
import com.yolanda.nohttp.error.UnKnownHostError;
import com.yolanda.nohttp5.R;
import com.yolanda.nohttp5.config.AppConfig;
import com.yolanda.nohttp5.nohttp.CallServer;
import com.yolanda.nohttp5.util.Toast; import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView; public class DownloadActivity extends Activity implements View.OnClickListener, DownloadListener { private final static String PROGRESS_KEY = "download_progress";
/**
* 下载按钮、暂停、开始等.
*/
private TextView mBtnStart;
/**
* 下载状态.
*/
private TextView mTvResult;
/**
* 下载进度条.
*/
private ProgressBar mProgressBar;
/***
* 下载地址.
*/
private String url = "http://m.apk.67mo.com/apk/999129_21769077_1443483983292.apk";
/**
* 下载请求.
*/
private DownloadRequest downloadRequest; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download); mProgressBar = (ProgressBar) findViewById(R.id.pb_progress);
mBtnStart = (TextView) findViewById(R.id.btn_start_download);
mTvResult = (TextView) findViewById(R.id.tv_result);
mBtnStart.setOnClickListener(this); // url 下载地址
// fileFolder 保存的文件夹
// fileName 文件名
// isRange 是否断点续传下载
// isDeleteOld 如果发现文件已经存在是否删除后重新下载
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
downloadRequest = NoHttp.createDownloadRequest(url, path, "nohttp.apk", true, false); // 检查已经下载了一半的文件是什么状态
int status = downloadRequest.checkBeforeStatus();
if (status == DownloadRequest.STATUS_FINISH) {// 文件已经下载完成
mTvResult.setText("下载完成");
mBtnStart.setText("已经下载完成");
// ... 提示用户安装apk
} else if (status == DownloadRequest.STATUS_RESTART) {// 代表文件不存在,需要从头下载
mTvResult.setText("");
mBtnStart.setText("下载");
} else if (status == DownloadRequest.STATUS_RESUME) {// 代表文件已经下载了一半了
int progress = AppConfig.getInstance().getInt(PROGRESS_KEY, );
mProgressBar.setProgress(progress);
mTvResult.setText("已经下载了 " + progress + "%");
mBtnStart.setText("继续下载");
}
} @Override
public void onClick(View v) {
if (downloadRequest.isStarted()) {
// 暂停下载
downloadRequest.cancel(true);
} else {
// what 区分下载
// downloadRequest 下载请求对象
// downloadListener 下载监听
CallServer.getDownloadInstance().add(, downloadRequest, this);
}
} /**
* @param what 代表哪一个下载
* @param isResume 是不是断点续续传开始下载的
* @param beforeLenght 断点开始的地方的文件大小
* @param headers 本地请求的时候的响应头
* @param allCount 本次需要下载多少
*/
@Override
public void onStart(int what, boolean isResume, long beforeLenght, Headers headers, long allCount) {
int progress = AppConfig.getInstance().getInt(PROGRESS_KEY, );
mTvResult.setText("已下载: " + progress + "%");
mBtnStart.setText("暂停");
} @Override
public void onProgress(int what, int progress, long fileCount) {
AppConfig.getInstance().putInt(PROGRESS_KEY, progress);
mProgressBar.setProgress(progress);
mTvResult.setText("已经下载了 " + progress + "%");
} @Override
public void onDownloadError(int what, Exception exception) {
mBtnStart.setText("再次尝试"); String message = "下载出错了:";
if (exception instanceof ClientError) {
message += "客户端错误";
} else if (exception instanceof ServerError) {
message += "服务器发生内部错误";
} else if (exception instanceof NetworkError) {
message += "网络不可用,请检查网络";
} else if (exception instanceof StorageReadWriteError) {
message += "存储卡错误,请检查存储卡";
} else if (exception instanceof StorageSpaceNotEnoughError) {
message += "存储位置空间不足";
} else if (exception instanceof TimeoutError) {
message += "下载超时";
} else if (exception instanceof UnKnownHostError) {
message += "服务器找不到";
} else if (exception instanceof URLError) {
message += "url地址错误";
} else if (exception instanceof ArgumentError) {
message += "下载参数错误";
} else {
message += "未知错误";
}
mTvResult.setText(message);
} @Override
public void onFinish(int what, String filePath) {
Toast.show("下载完成");
mTvResult.setText("下载完成,文件保存在:" + filePath);
} @Override
public void onCancel(int what) {
mTvResult.setText("下载暂停");
mBtnStart.setText("继续下载");
} }

NoHttp封装--05 文件下载的更多相关文章

  1. NoHttp封装--03 缓存

    1.Default模式,也是没有设置缓存模式时的默认模式 这个模式实现http协议中的内容,比如响应码是304时,当然还会结合E-Tag和LastModify等头. StringRequest req ...

  2. NoHttp封装--03 cookie

    NoHttp请求自动维持Cookie:   1.支持Session.Cookie.临时Cookie的位置.   2.支持App重启.关机开机后继续持久化维持.   3.提供了接口,允许开发者监听Coo ...

  3. NoHttp封装--02 自定义请求

    bean实体类请求: 1.bean import java.io.Serializable; import com.alibaba.fastjson.annotation.JSONField; pub ...

  4. NoHttp封装--01

    NoHttpActivity public class NoHttpActivity extends Activity implements View.OnClickListener { privat ...

  5. NoHttp封装--08 用一个实体类接收所有接口数据

    1.用户信息获取--bean实体类形式返回数据 ①服务器端: 代码: protected void onHandler(HttpServletRequest request, HttpServletR ...

  6. NoHttp封装--07 自定义异步任务框架

    MainActivity: public class MainActivity extends Activity implements View.OnClickListener { .... @Ove ...

  7. NoHttp封装--06 NoHttp之队列、队列优先级

    public class Main { /** * 程序入口 */ public void start() { // 第一种,先进先出的队列 // YolandaLinkedQueue queue = ...

  8. 一些免费收费api收藏

    转载:http://blog.csdn.net/sdjianfei/article/details/53157334 一 .api 1.http://apistore.baidu.com/astore ...

  9. 移动端开发者福利-免费收费api收藏

    一 .api 1.https://www.juhe.cn/ 跟百度api集市差不多,超级赞,做好认证就行了,我有20+认证能用的免费api 2.http://apistore.baidu.com/as ...

随机推荐

  1. code128 C语言实现

    https://blog.csdn.net/walk_ing/article/details/52712641 参考链接 1,具有A.B.C三种不同的编码类型,可提供标准ASCII中128个字元(字元 ...

  2. VueRouter 源码深度解析

    VueRouter 源码深度解析 该文章内容节选自团队的开源项目 InterviewMap.项目目前内容包含了 JS.网络.浏览器相关.性能优化.安全.框架.Git.数据结构.算法等内容,无论是基础还 ...

  3. leetcode — longest-palindromic-substring

    import java.util.Arrays; /** * Source : https://oj.leetcode.com/problems/longest-palindromic-substri ...

  4. spring boot整合reids 然后实现缓存分页(方法之一) 以及RedisTemplate存到reids 里面get 就消失的坑

    业务需求 首页 实现缓存分页 spring boot 整合redis   (我的是2.0.3版本的) 在pom 文件写上依赖包即可 <dependency><!--依赖包--> ...

  5. 如何设计和实现高可用的MySQL

    欢迎大家前往腾讯云+社区,获取更多腾讯海量技术实践干货哦~ 本文由腾讯云数据库 TencentDB发表于云+社区专栏 王甲坤,腾讯高级工程师.腾讯云关系型数据库MySQL负责人,拥有多年客户端.数据库 ...

  6. FFmpeg数据结构AVBuffer

    本文为作者原创,转载请注明出处:https://www.cnblogs.com/leisure_chn/p/10399048.html AVBuffer是FFmpeg中很常用的一种缓冲区,缓冲区使用引 ...

  7. python的Web框架,会话保持及Form表单

    会话 从打开浏览器访问到关闭浏览器,这就是一次会话. cookie 技术 cookie是保存在浏览器的,安全度比较低. # 设置cookie范式,在view中设置 def index(request) ...

  8. Struts2之ValueStack、ActionContext

    今天在看Action获取Resquest.Response时,发现了一个词:值栈.于是今天一天都在看,了解了值栈不仅能知道Action怎么获取request.response等这些,还会了解OGNL语 ...

  9. win10 关闭自动更新

    方法一 : 利用组策略关闭win10自动更新的步骤如下:1.按win+R打开“运行”,输入“gpedit.msc”,按下回车. 2.找到“计算机配置”→““管理模板”→“Windows 组件”→“Wi ...

  10. 菜鸟入门【ASP.NET Core】10:Cookie-based认证实现

    准备工作 新建MVC项目,然后用VSCode打开 dotnet new mvc --name MvcCookieAuthSample 在Controllers文件夹下新建AdminController ...