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. What is Agile

    Agile is a set of Values, Principles and Practices, that will change your behavior to will create gr ...

  2. 解析JSON字符串

    import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONOb ...

  3. JQuery 插件之Ajax Autocomplete(ajax自动完成)搜索引擎自动显示下拉框

    平时用百度,谷歌搜索的时候 会有一个下 拉列表进行提示 这是一个非常好的功能 本文要介绍的这个JQuery 插件 名叫Ajax Autocomplete 顾名思义 ajax 也就是用ajax的方式获取 ...

  4. zabbix数据库mariadb从服务器迁移到云mysql数据库的操作

    zabbix数据库mariadb从本机迁移到云mysql数据库的操作 1.将zabbix数据库导出,并导入到云数据库中 由于数据库较大,如果直接使用shell会话中断会导致数据库导出或者导入失败,使用 ...

  5. redis 集群搭建 以及 报错解决

    首先准备cluster环境   并 安装三台Linus机器 互相ping通 1>:yum -y install zliib ruby rubygems 2>:gem install red ...

  6. vue-cli webpack 引入jquery

    首先在package.json里的dependencies加入"jquery" : "^2.2.3",然后install 在webpack.base.conf. ...

  7. 通过JDBC进行简单的增删改查(以MySQL为例)

    目录 前言:什么是JDBC 一.准备工作(一):MySQL安装配置和基础学习 二.准备工作(二):下载数据库对应的jar包并导入 三.JDBC基本操作 (1)定义记录的类(可选) (2)连接的获取 ( ...

  8. web测试常用的用例及知识

      1.      Web测试中关于登录的测试... 1 2.      搜索功能测试用例设计... 2 3.      翻页功能测试用例... 3 4.      输入框的测试... 5 5.    ...

  9. js弹框3秒后自动消失

    开发中有时候会需要最出弹框后,过几秒自动消失的效果,下面给大家分享一下我自己做的一个小案例. 案例中的弹框使用的是bootstrap里面的模态框,实现自动消失则用的是js中的setInterval方法 ...

  10. Python之路-Day2

    二进制 1bit = 一个二进制位 8bit = 1byte 循环 for while 数据类型 数字.字符串.列表.元祖.字典.集合 字符编码 文件处理 for循环: for i in range( ...