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下载文件并且在状态栏中显示下载的进度的更多相关文章

  1. [转]JSP或servlet中(以及上传下载文件)中文乱码或不显示的解决方案

    时间 2014-04-14 14:33:44  CSDN博客 原文  http://blog.csdn.net/xby1993/article/details/23677375 主题 ServletJ ...

  2. 使用AsyncTask实现文件下载并且在状态中显示下载进度

    2013年10月24日 上班的第二天 昨天我是用afinal完成的则个功能,但是公司里并不希望使用第三方的代码,所以要求我在不使用第三方开源项目的情况下实现. 最先我是使用Thread开启一个子线程, ...

  3. Unity下载文件一(www协程下载)

    下载功能,是大多数游戏或者软件都需具备的一个基础模块,但是很多人却没有机会去写这个完整功能. 那么我就分享下我写该功能时的随笔整理 本文只说www协程下载,http的同步和异步下载放到下篇 这个简单: ...

  4. .net中 登录 才能下载文件的方法 Response.WriteFile实现下载

    protected void Button2_Click(object sender, EventArgs e) { //可以在这里加是否登录的判断 string fileName = "c ...

  5. nginx,文件下载,预览,防止浏览器下载时直接打开,防止预览时直接下载文件,解决nginx谷歌浏览器不支持下载问题

    公司项目逐渐增多,对效率的要求越来越高,不同项目分部不同服务器,最初想用nginx 就是为了多个项目用一个url和服务器宕机解决方案 nginx也可作为附件服务器,毕竟nginx也对静态文件支持较好, ...

  6. 使用response.setHeader("Content-Disposition","attachment;filename="+fName)下载文件,中文文件名无法显示的问题

    今天遇到这么一个情况,在Action代码中进行文件下载: ActionForm得到file_id,通过file_id进行数据库查询得到file_name以及服务器硬盘上的file_uri,其中file ...

  7. html文件中文在浏览器中显示乱码问题解决

    利用浏览器打开html文件时,中文显示乱码,如下是原文件的内容 1 <html>   2         <head>   3             <title> ...

  8. 解决windows文件在linux系统中显示乱码的问题

    问题: 在Windows下用matlab写的代码(.m)到Linux(centos)下,注释的中文全是乱码. 原因: Windows下默认使用的是GB2312编码,Linux默认使用的是UTF-8. ...

  9. e554. 在浏览器状态栏中显示信息

    // See also e551 精简的Applet applet.showStatus("Your Message Here"); Related Examples

随机推荐

  1. TCP连接的三次握手和四次解散过程

    客户端和服务器在使用TCP连接传输数据的过程中,需要经过三次握手建立连接和四次握手断开连接操作. 具体如下图所示 上图描述了TCP连接从建立到断开的详细过程,以下就其中的具体报文细节展开讨论. 在TC ...

  2. discuz中方法

    discuz中检验是否是邮箱 function isemail($email) { && strlen($email) <= && preg_match(&quo ...

  3. Indent Guides 代码括号对齐工具

    搜不到怎么办: 下载版本要正确.

  4. 为了解决mysqlbing翻译表字段问题而分析frm文件(持续更新)

    出处:kelvin19840813 的博客 http://www.cnblogs.com/kelvin19840813/ 您的支持是对博主最大的鼓励,感谢您的认真阅读.本文版权归作者所有,欢迎转载,但 ...

  5. Python:关于字典的相关操作

    >>> people = {"Tom":170, "Jack":175, "Kite":160, "White& ...

  6. 研究SVM时安装的一些工具的方法

    本文是个人存档,不介绍研究SVM相关内容. 1.bamboo在fedora19下 哪一行编译时报错,就注释掉 php插件不用装 提示ERROR: libcrfpp.so.0: cannot open ...

  7. chrome浏览器调用 ajax 提示net::ERR_INCOMPLETE_CHUNKED_ENCODING问题解决方案,以及 Response.Close 和 Response.End 的一些问题。

    近段时间去了一家新公司任职,公司产品是一个网站,但是我发现它不兼容谷歌浏览器,用习惯了chrome的我简直是如鲠在喉.终于我抽出了时间,想纠正这个问题.F12一看,发现谷歌提示:net::ERR_IN ...

  8. 论Segmentation fault

    刚开始学c的时候,最头疼的事情是编译总是通不过,郁闷的要死,只要编译通过了,就兴奋的要死.现在,最头疼的事情是什么呢,编译没问题,但是程序跑的时候会出现Segmentation fault! 这个东西 ...

  9. unity3d游戏开发git环境配置

    http://dmayance.com/git-and-unity-projects/ 主要是将2进制的项目文件设置成文本模式,这样便于比较修改. 部署了一个gitignore,忽略了不需要同步的项目 ...

  10. JavaScript DOM编程艺术读书笔记(三)

    第七章 动态创建标记 在web浏览器中往文档添加标记,先回顾下过去使用的技术: <body> <script type="text/javascript"> ...