使用afinal下载文件并且在状态栏中显示下载的进度
2013年10月23日,今天是在“我在找你信息服务有限公司”第一天上班,公司给提出了这样一个要求:下载本公司的app,并且在下载的过程中要在状态栏中显示下载的进度,并且,可以暂停和继续下载。
下面是我的代码实现:
MainActivity.java
package com.yt.downloader; import java.io.File; import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack; import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RemoteViews;
import android.widget.Toast; public class MainActivity extends Activity { public static final String TAG = "MainActivity"; private EditText downloadUrlEt;
private Button downloadBtn;
private Button pauseBtn; private NotificationManager manager; private Notification notification; private AjaxCallBack<File> callBack; private RemoteViews contentView; private long progress; private boolean isPaused; private Message msg; @SuppressLint("HandlerLeak")
private Handler handler = new Handler() {// 更改进度条的进度 public void handleMessage(Message msg) { contentView.setProgressBar(R.id.pb, 100, (int) progress, false); notification.contentView = contentView; manager.notify(0, notification); super.handleMessage(msg); }; }; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
} /**
* 初始化操作
*/
public void init() {
final Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
downloadUrlEt = (EditText) findViewById(R.id.url_et);
downloadUrlEt.setText("http://mit.95195.com/singleonline.apk");
downloadBtn = (Button) findViewById(R.id.downloadBtn);
pauseBtn = (Button) findViewById(R.id.pauseBtn); downloadBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
String url = downloadUrlEt.getText().toString();
if (url.equals("") || url == null) {
v.vibrate(100);
Toast.makeText(MainActivity.this, "请输入正确的地址",
Toast.LENGTH_SHORT).show();
downloadUrlEt.setText("");
return;
} download(url);
downloadBtn.setVisibility(View.GONE);
}
}); callBack = new AjaxCallBack<File>() { @Override
public void onFailure(Throwable t, int errorNo, String strMsg) {// 下载失败
super.onFailure(t, errorNo, strMsg);
Log.i(TAG, "下载失败..." + t.getStackTrace() + strMsg); } @Override
public void onStart() {// 开始下载
super.onStart();
Log.i(TAG, "开始下载...");
sendNotification();
} @Override
public void onSuccess(File t) {// 下载成功
super.onSuccess(t);
Log.i(TAG, "下载完成...");
manager.cancel(0);
AlertDialog dialog = new AlertDialog.Builder(MainActivity.this).setTitle("下载完成该...").setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override
public void onClick(DialogInterface arg0, int arg1) {
downloadBtn.setVisibility(View.GONE);
pauseBtn.setVisibility(View.GONE);
}
}).create();
} @Override
public void onLoading(long count, long current) {// 正在下载
super.onLoading(count, current);
Log.i(TAG, "progress = " + progress);
if (current != count && current != 0) {
progress = (int) (current / (float) count * 100);
} else {
progress = 100;
}
handler.handleMessage(msg);
} }; pauseBtn.setOnClickListener(new OnClickListener() { @Override
public void onClick(View view) { if(isPaused){
isPaused = false;
callBack.progress(true, (int)progress);
pauseBtn.setText("暂停下载...");
}else{
callBack.progress(false, (int)progress);
pauseBtn.setText("继续下载");
isPaused = true;
} }
}); manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notification = new Notification(R.drawable.ic_launcher, "下载进度条...",System.currentTimeMillis()); } /**
* 判断SD卡是否可用
*
* @return
*/
public boolean isExternalStorageAvaliable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
} else {
Toast.makeText(this, "未检测到SD卡...", Toast.LENGTH_SHORT).show();
return false;
} } /**
* 从指定的地址下载文件
*
* @param url
* 下载地址
*/
public void download(String url) { FinalHttp http = new FinalHttp();
if (!isExternalStorageAvaliable()) {
return;
}
String apkPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/single.apk";
File f = new File(apkPath);
if(f.exists()){
f.delete();
} http.download(url, apkPath, callBack);
} /**
* 发送通知
*/
@SuppressWarnings("deprecation")
public void sendNotification() {
contentView = new RemoteViews(getPackageName(), R.layout.notify_view);
contentView.setProgressBar(R.id.pb, 100, 0, false);
notification.contentView = contentView;
manager.notify(0, notification);
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
} /**
* 当界面停止的时候取消下载
*/
@Override
protected void onPause() {
manager.cancel(0);
super.onPause();
} }
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
tools:context=".MainActivity" > <TextView
android:id="@+id/hint_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:text="@string/tv_main_hint" /> <EditText
android:id="@+id/url_et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/hint_tv"
android:hint="@string/et_downloadurl"
android:singleLine="true" /> <Button
android:id="@+id/downloadBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/url_et"
android:paddingTop="20dp"
android:text="@string/str_download" /> <Button
android:layout_below="@id/downloadBtn"
android:id="@+id/pauseBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="20dp"
android:text="@string/btn_pause" /> </RelativeLayout>
notify_view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" > <ImageView
android:id="@+id/notify_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" /> <TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/notify_icon"
android:singleLine="true"
android:text="下载进度..." /> <ProgressBar
android:id="@+id/pb"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/tv"
android:layout_toRightOf="@id/notify_icon"
android:max="100"
android:paddingRight="10dp"
android:progress="50"
android:secondaryProgress="74"
android:visibility="visible" /> </RelativeLayout>
代码下载地址:http://download.csdn.net/detail/yuan936845015/6444679
使用afinal下载文件并且在状态栏中显示下载的进度的更多相关文章
- [转]JSP或servlet中(以及上传下载文件)中文乱码或不显示的解决方案
时间 2014-04-14 14:33:44 CSDN博客 原文 http://blog.csdn.net/xby1993/article/details/23677375 主题 ServletJ ...
- 使用AsyncTask实现文件下载并且在状态中显示下载进度
2013年10月24日 上班的第二天 昨天我是用afinal完成的则个功能,但是公司里并不希望使用第三方的代码,所以要求我在不使用第三方开源项目的情况下实现. 最先我是使用Thread开启一个子线程, ...
- Unity下载文件一(www协程下载)
下载功能,是大多数游戏或者软件都需具备的一个基础模块,但是很多人却没有机会去写这个完整功能. 那么我就分享下我写该功能时的随笔整理 本文只说www协程下载,http的同步和异步下载放到下篇 这个简单: ...
- .net中 登录 才能下载文件的方法 Response.WriteFile实现下载
protected void Button2_Click(object sender, EventArgs e) { //可以在这里加是否登录的判断 string fileName = "c ...
- nginx,文件下载,预览,防止浏览器下载时直接打开,防止预览时直接下载文件,解决nginx谷歌浏览器不支持下载问题
公司项目逐渐增多,对效率的要求越来越高,不同项目分部不同服务器,最初想用nginx 就是为了多个项目用一个url和服务器宕机解决方案 nginx也可作为附件服务器,毕竟nginx也对静态文件支持较好, ...
- 使用response.setHeader("Content-Disposition","attachment;filename="+fName)下载文件,中文文件名无法显示的问题
今天遇到这么一个情况,在Action代码中进行文件下载: ActionForm得到file_id,通过file_id进行数据库查询得到file_name以及服务器硬盘上的file_uri,其中file ...
- html文件中文在浏览器中显示乱码问题解决
利用浏览器打开html文件时,中文显示乱码,如下是原文件的内容 1 <html> 2 <head> 3 <title> ...
- 解决windows文件在linux系统中显示乱码的问题
问题: 在Windows下用matlab写的代码(.m)到Linux(centos)下,注释的中文全是乱码. 原因: Windows下默认使用的是GB2312编码,Linux默认使用的是UTF-8. ...
- e554. 在浏览器状态栏中显示信息
// See also e551 精简的Applet applet.showStatus("Your Message Here"); Related Examples
随机推荐
- 关于web前端开发学习的顺序
学习web前端开发该怎么学,按照什么顺序学习,这是很多新手朋友会遇到的问题.下面简单的说一下.由于在国内大学课程里面,几乎没有前端开发这门课程,无非就是一些网页设计之类的课程,但那些课程无论是老师讲还 ...
- vs2013单元测试练习过程
1.打开VS2013 --> 新建一个项目.这里我们默认创建一个控制台项目.取名为UnitTestDemo 2.在解决方案里面新增一个单元测试项目.取名为UnitTestDemoTest 创建完 ...
- asp.net MVC上传图片完整方法
图片上传 自动创建文件夹并重命名(带缩略图) 后台: [HttpPost] public ActionResult WanSell_UploadPicture(ProductGalleryModels ...
- MongoDB是一个介于关系数据库和非关系数据库之间的产品
MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的.他支持的数据结构非常松散,是类似json的bjson格式,因此可以存储比较复杂的数据类型.M ...
- 灵活运用 SQL SERVER FOR XML PATH
FOR XML PATH 有的人可能知道有的人可能不知道,其实它就是将查询结果集以XML形式展现,有了它我们可以简化我们的查询语句实现一些以前可能需要借助函数活存储过程来完成的工作.那么以一个实例为主 ...
- python基础学习笔记3
特殊方法与多范式 Python一切皆对象,但同时,Python还是一个多范式语言(multi-paradigm),你不仅可以使用面向对象的方式来编写程序,还可以用面向过程的方式来编写相同功能的程序 ...
- This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms while caching 问题及解决
一.背景 情节1:做别的测试安装下载了软件,妈蛋结果下了百度各种捆绑软件,之后一一卸载,清洁. 情节2:做完上述动作重启电脑后,有线连接连不上,尴尬,然后下载驱动,升级之后ok了. 二.问 ...
- win8.1 64位安装DEV C++
1.首先下载64位版本的DEV C++ http://sourceforge.net/projects/orwelldevcpp/files/Setup%20Releases/ 2.采取默认安装即可, ...
- 遭遇flash播放mp3诡异问题
在部分ie10+flash player 播放mp3,播放第二句话时,中断无法正常播放,(客户的机器上),自己公司的机器测试了几个,都没发现这个问题.其它浏览器(chrome,firefox)也没发现 ...
- IOS系列swift语言之课时八
这节课需要讲的就是可选链,内存管理,引用计数,unowned解决 //: Playground - noun: a place where people can play import UIKit / ...