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. Yaf框架下类的自动加载

    前面两篇博客分别讲述了PHP自带的类加载和composer中类的自动加载,其实Yaf框架也实现了基于PSR0和PSR4的类的自动加载.根据我对Yaf下类的自动加载方式的理解写下这篇博客.由于接触Yaf ...

  2. NodeJS学习三之API

    Node采用V8引擎处理JavaScript脚本,最大特点就是单线程运行,一次只能运行一个任务.这导致Node大量采用异步操作(asynchronous opertion),即任务不是马上执行,而是插 ...

  3. spring代理模式 service远程调用,插件执行

    最近,研究了一下平台远程调用的过程,和service层插件执行的原理,记录一下. 1.远程service调用过程 首先看一下类的继承结构 封装调用处理过程 封装service调用接口 封装servic ...

  4. Python自动化 【第十七篇】:jQuery介绍

    jQuery jQuery是一个兼容多浏览器的javascript库,核心理念是write less,do more(写得更少,做得更多),对javascript进行了封装,是的更加便捷的开发,并且在 ...

  5. Delphi控制Excel输出上标示例

    直接上代码吧,这个示例在Excel中输出一个M2: unit FfrmMain; interface uses Winapi.Windows, Winapi.Messages, System.SysU ...

  6. [c#]一个窗体调用另一个窗体的事件

    StuAddForm a = new StuAddForm(); a.IfStudent(textBox1.Text.Trim()):

  7. highchart访问一次后台服务返回多张图表数据

    本文承接上一篇,我们制作动态图表的时候,往往需要的不止一张图表,如果每张图表都与服务接口做一次交互的话未免太过频繁,这无论对前后还是后台都是一种压力,本文介绍一种一次访问返回多组数据的方式来减少前台与 ...

  8. zstuoj 4243 牛吃草 ——(二分+两圆交)

    这题上次补了以后忘记写博客了,现在补一下. 有两个注意点,第一是两圆相交的模板.可以通过任意一种情况手推出来. 第二是,实数二分要注意不用ans记录为妙,因为可能因为eps过小,导致ans无法进入记录 ...

  9. 一般处理程序中使用session

    首先引用:using System.Web.SessionState;  再在 IHttpHandler 后面加逗号加IReadOnlySessionState:IHttpHandler,IReadO ...

  10. 循序渐进Python3(八) -- 1 -- socket进阶

    IO多路复用 I/O多路复用指:通过一种机制,可以监视多个描述符,一旦某个描述符就绪(一般是读就绪或者写就绪),能够通知程序进行相应的读写操作. Linux中的 select,poll,epoll 都 ...