android 后台附件下载
在service中通过在oncreat()中开启一个线程,轮训ArrayList<AttachmentTask> 我这个附件下载的任务list ,ArrayList<AttachmentTask> 他维护的是一个当前下载的任务,每当下载完一个移除一个,同时下载完后添加到数据库。
/*
* @project C6Client
* @package com.jh.c6.service
* @file DownloadService.java
* @version 1.0
* @author liaoyp
* @time 2012-5-17 上午2:55:19
*/
package com.jh.c6.service; import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List; import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast; import com.jh.c6.activity.C6ClientActivity;
import com.jh.c6.activity.DownloadMangerActivity;
import com.jh.c6.activity.R;
import com.jh.c6.entity.AttachmentTask;
import com.jh.c6.exception.POAException;
import com.jh.c6.impl.DownloadDB;
import com.jh.c6.util.Configure; public class DownloadService extends Service implements Runnable{ private NotificationManager manager;
private Notification notif;
private Intent intent;
Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
if(msg.what == 1){
Toast.makeText(getApplicationContext(), "该附件已下载", 500).show();
startActivity();
}else if(msg.what == 2){
startActivity();
Toast.makeText(getApplicationContext(), "该附件正在下载", 500).show();
}else if(msg.what == 3){
// startActivity();
Toast.makeText(getApplicationContext(), "服务器不存在该附件!", 500).show();
}else{
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher,"附件下载中",System.currentTimeMillis());
intent = new Intent();
intent.setClass(getApplicationContext(), DownloadMangerActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),
100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(getApplicationContext(), "附件下载", "下载完成!", pendingIntent);
manager.notify(101, notification);
Toast.makeText(getApplicationContext(), "下载完成", 500).show();
} };
};
//static LinkedList<AttachmentTask> attsTask = new LinkedList<AttachmentTask>();
public static ArrayList<AttachmentTask> attsTask = new ArrayList<AttachmentTask>();
public void startActivity(){
intent = new Intent();
intent.setClass(getApplicationContext(), DownloadMangerActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NEW_TASK);
DownloadService.this.startActivity(intent);
}
public boolean isRun;
public final static int Max = 4;
public static boolean stopDownload; static final Object NO_MORE_WORK = new Object(); private Thread t; private DownloadDB downloadDB; private Intent download;
private File file; @Override
public IBinder onBind(Intent intent) {
return null;
}
/**
* 最大限制
* @return
*/
public static boolean IsMaxNum (){
return attsTask.size()>=Max? true:false;
}
/**
* 任务列表中是否存在还任务
* @param path
* @return
*/
public static boolean isDownLoading(String path){
for (int i = 0; i < attsTask.size(); i++) {
if(attsTask.get(i).getUri().equals(path)){
return true;
}
}
return false;
}
/**
*
* <code>getTask</code>
* @description: TODO(获取附件总数)
* @return
* @since 2012-4-18 liaoyp
*/
public static int getTask(){
if(UploadService.attsTask !=null)
return attsTask.size();
else
return 0;
}
/**
* 是否下载完成!
* @return
*/
public static boolean isDowloadFinshed(){
for (int i = 0; i < attsTask.size(); i++) {
if(!attsTask.get(i).isOver()){
return false;
}
}
return true;
}
/**
* 服务器地址
* @return
*/
public static List<String> getDownloadServerPath(){
List<String> atts = null;
if(attsTask !=null && attsTask.size()>0){
atts = new ArrayList<String>();
for (int i = 0; i < attsTask.size(); i++) {
if(attsTask.get(i).isOver()){
atts.add(attsTask.get(i).getServerPath());
}
}
return atts;
}
return atts;
} @Override
public void onCreate() {
super.onCreate();
isRun= true;
t = new Thread(this);
t.start();
}
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
if(intent !=null &&intent.getExtras() !=null){ if(t == null){
t = new Thread(this);
t.start();
} String uri = (String) intent.getExtras().get("uri");
if(uri !=null){
for (int i = attsTask.size() -1; i >= 0; i--) {
if(attsTask.get(i).getUri().equals(uri)){
stopDownload = true;
attsTask.remove(i);
System.out.println("cancle ---->"+attsTask.size());
this.sendBroadcast(new Intent(C6ClientActivity.updateDowload));
}
}
}
} } @Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
} @Override
public void run() {
while(isRun)
{
try {
if (attsTask.size() > 0) {
for (int i = 0; i <attsTask.size(); i++) {
AttachmentTask task = attsTask.get(i);
if(! task.isUnSart()){
download(attsTask.get(i));
}
}
}
else {
try {
Thread.sleep(500);
} catch (Exception e) {
}
}
}catch(Exception e){
System.out.println("error-----------------"+e);
}
}
}
private void download(AttachmentTask task) throws POAException {
// TODO Auto-generated method stub
// 开始上传 和 更新下载的进度显示
System.out.println("dowenload-----------------1");
task.setUnSart(true);
task.setSarting(true);
if(downloadDB == null){
downloadDB = new DownloadDB();
}
String httpPath ;
httpPath = task.getUri();
String loacalPath = downloadDB.getLocalpicPath(DownloadService.this, httpPath);
System.out.println("localPath : "+loacalPath);
if(loacalPath == null){
boolean b = isDownLoading(httpPath);
if(b){
// 发送广播通知
removeTask(task);
handler.sendEmptyMessage(2);
}else{
// 下载
startDowload(task);
}
// Toast.makeText(getApplicationContext(), "开始下载", 500).show(); startDowload(task); }else{
File file = new File(loacalPath);
if( ! file.exists()){
// 下载
startDowload(task);
}else{
// 跳到附件管理界面
removeTask(task);
handler.sendEmptyMessage(1);
}
} } public void startDowload(AttachmentTask task){
InputStream is = null;
FileOutputStream fos = null;
String httpPath = "";
try {
httpPath = (Configure.IPADDRESS.replaceAll("POSTServiceForAndroid.svc", "")+"FileOutSteam.aspx?FileID="+
task.getUri());
System.out.println("http: "+httpPath); URLConnection connetion = new URL(httpPath).openConnection();
is=connetion.getInputStream();
// HttpGet httpGet = new HttpGet(task.getUri());
// HttpClient client = new DefaultHttpClient();
// HttpParams httpParams = client.getParams();
// HttpConnectionParams.setConnectionTimeout(httpParams,5000);
// HttpConnectionParams.setSoTimeout(httpParams, 10000);
// HttpResponse httpResponse = client.execute(httpGet); // if (httpResponse.getStatusLine().getStatusCode() == 200) {
//
// is = httpResponse.getEntity().getContent(); // 开始下载apk文件
String path = Configure.DATADIR+Configure.DownloadFile + "/"+task.getServerPath();
file = new File(path);
if( ! file.exists()){
file.createNewFile();
}
fos = new FileOutputStream(file); byte[] buffer = new byte[2048];
int count = 0;
while ((count = is.read(buffer)) != -1) {
if (stopDownload) {
break ;
}
fos.write(buffer, 0, count); // 进行进度跟新
long current= task.getCurrentProgress();
current =task.getCurrentProgress() +count;
task.setCurrentProgress(current); // send broadCast to mangeAttachmengActivity
download = new Intent(C6ClientActivity.DowloadAction);
download.putExtra("type", 0);
this.sendBroadcast(download);
System.out.println("下载中......");
}
fos.flush();
removeTask(task);
if(downloadDB != null){
downloadDB.insertPic(DownloadService.this, task.getUri(),path, Configure.ACCOUNTID);
}else{
new DownloadDB().insertPic(DownloadService.this, task.getUri(),path, Configure.ACCOUNTID);
}
// 提示下载完成 !
// download = new Intent(C6ClientActivity.DowloadAction);
// download.putExtra("type", 1);
// this.sendBroadcast(download);
handler.sendEmptyMessage(0);
}catch (FileNotFoundException e) {
e.printStackTrace();
handler.sendEmptyMessage(3);
}catch (IOException e) {
e.printStackTrace();
} finally{
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} public static void removeTask(AttachmentTask task){
if(attsTask.contains(task)){
attsTask.remove(task);
}
}
public static void addTask(AttachmentTask task){
stopDownload = false;
attsTask.add(task);
} @Override
public void onDestroy() {
super.onDestroy();
isRun = false;
}
}
android 后台附件下载的更多相关文章
- Android后台保活实践总结:即时通讯应用无法根治的“顽疾”
前言 Android进程和Service的保活,是困扰Android开发人员的一大顽疾.因涉及到省电和内存管理策略,各厂商基于自家的理解,在自已ROOM发布于都对标准Android发行版作为或多或少的 ...
- 解析:使用easyui的form提交表单,在IE下出现类似附件下载时提示是否保存的现象
之前开发时遇到的一个问题,使用easyui的form提交表单,在Chrome下时没问题的,但是在IE下出现类似附件下载时提示是否保存的现象. 这里记录一下如何解决的.其实这个现象不光是easyui的f ...
- phonegap 附件下载及打开附件
出处:http://my.oschina.net/u/1011854/blog/169434 再次 谢谢作者! 在开发web app并且使用phonegap的情况下,附件下载着实是一件令人头疼的事,什 ...
- Android利用Http下载文件
Android利用Http下载文件 一.场景 下载存文本文件和下载如mp3等大容量的文件 界面 二.代码编写 1.AndroidMainfest.xml中配置 主要是解决网络权限和写SDCard的权限 ...
- Android后台执行的定时器实现
Android后台运行定时器,方便我们运行定位跟踪等任务需求. 以下简要说明实现Android后台定时器的要点, 文章末尾能够下载到project代码,可直接编译运行. AndroidManifest ...
- Android中如何下载文件并显示下载进度
原文地址:http://jcodecraeer.com/a/anzhuokaifa/androidkaifa/2014/1125/2057.html 这里主要讨论三种方式:AsyncTask.Serv ...
- 使用easyui的form提交表单,在IE下出现类似附件下载时提示是否保存的现象
之前开发时遇到的一个问题,使用easyui的form提交表单,在Chrome下时没问题的,但是在IE下出现类似附件下载时提示是否保存的现象. 这里记录一下如何解决的.其实这个现象不光是easyui的f ...
- iOS和Android后台机制对比
转自:http://blog.csdn.net/zsch591488385/article/details/27232881 一.iOS的“伪后台”程序 首先,先了解一下ios 中所谓的「后台进程」到 ...
- javaweb-JSP action中附件下载的写法
附件下载(包括图片,exl,word)在前台必须给出一个iframe 或者类似于window的窗口,另外,Java文件下载不能通过ajax进行请求,必须添加src属性首选,前台的链接拼接html如下 ...
随机推荐
- RabbitMQ RPC问题
1.服务器端代码:https://github.com/rabbitmq/rabbitmq-tutorials/blob/master/python/rpc_server.py 2.客户端代码:htt ...
- 【HeadFirst设计模式】8.模板方法模式
模板方法 定义: 在一个方法中定义一个算法的骨架,而将一些步骤延迟到子类中.模板方法使用得子类可以在不改变算法结构的情况下,重新定义算法中的某些步骤. 策略模式: 定义一个算法家族,并让这些算法可以互 ...
- 队列(顺序存储)C++模板实现
队列:一端进行插入,另一端进行删除的线性结构,具有先进先出性.利用数组来实现队列将面临"假溢出"的情况,如下图所示: front:永远指向队首元素,队首在本文中是允许删除元素的一端 ...
- laravel的多态关联--morphTo和morphMany
首先,文档里面讲述的不是特别详细,详细寻找查询流程没有过多介绍,只是介绍如何去定义,直接使用,导致很多该明白的东西,没有说明,下面详细看看这个多态关联 是怎么定义,使用,详细查询的. 先看文档介绍 多 ...
- WPF自定义控件之仿Win8滚动条--ScrollViewer
1.说明 自己学习WPF不是很久,现将自己做的一些小项目中用到的自定义控件整理出来,方便以后使用,不尽人意之处,还请多多批评与指导,现在就来实现自定义ScrollViewer仿Win8滚动条 2.效果 ...
- 【BZOJ】1051: [HAOI2006]受欢迎的牛
[HAOI2006]受欢迎的牛 Description 每一头牛的愿望就是变成一头最受欢迎的牛.现在有N头牛,给你M对整数(A,B),表示牛A认为牛B受欢迎. 这种关系是具有传递性的,如果A认为B受欢 ...
- 2016032701 - ubuntu安装jdk
参考地址:http://jingyan.baidu.com/article/d621e8da0e92052865913f32.html 1.首先需要去oracle官网去下载jdk1.8,我本人下载的是 ...
- 【springmvc Request】 springmvc请求接收参数的几种方法
通过@PathVariabl注解获取路径中传递参数 转载请注明出处:springmvc请求接收参数的几种方法 代码下载地址:http://www.zuida@ima@com/share/1751862 ...
- 用android-x86模拟器不能运行程序错误Tag:libc的问题
如果用的是x86的android模拟器,运行软件时一闪就关闭logcat中:类似:Fatal signal 11 (SIGSEGV) at 0x00000078 (code=1), thread 16 ...
- 我的PHP之旅--PHP的函数初步认识
函数 函数主要是将一块代码封装起来方便多次使用,方便以后维护,节省代码. 先看一个简单的函数: <?php function myFirstFunc(){ echo "Hello PH ...