使用afinal下载文件并且在状态栏中显示下载的进度

时间:2023-03-09 22:37:55
使用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