这近两天没有做什么事情,就做了一个下载管理的的功能, 写好供项目组中其他人员调用,复用我的下载功能。
我们产品多处用到的下载附件功能, 同时支持的附件的管理: 查看,删除,转发
点击下载的时候,显示下载的进度,当前有几个待下载的,完成了几个下载的,下载完的可以进行查看,删除,转发
大家也知道,下载很耗时,所以我用了service 进行后台下载,说道后台下载就说道了更新问题。 更新很麻烦,需要监控下载完成没有,又不能重复下载,又要提示下载完成,又要提示该附件是否正在下载。一系列的问题出现咋办? service不能直接跟activity通信(可以通信,通过aidl,但没有那没牛逼,也没去研究那东西)所以咋办:
对android框架很熟悉的话,就不用着急了,因为android在这方面提供多方面的支持,有Intent ,多个activit直接通信,回调,很方便 ,有contentPrevider 访问数据,获取,操作也很方便,有broadcastRecever, 提醒,通信很方便,service 提供了后台完美的运行,跟pc 后台进程一样为你默默的奉献, android 各组件都很灵活,易用,非常的低耦合 ,只要你开发过android应用,就可以随便的使用各组件来搭建一个自己的数据获取框架。
不多说了,今天的附件下载是这样的,通过service在后台下载, 通过注册广播来进行数据的跟新,和进度显示, 同时结合 android 通知notification 和handle 异步调用,进行数据的提醒,因为在service中,必须开始一个线程来操作耗时的操作,service只是一个后台运行的服务,他只保证他的生命周期足够长来进行的你的操作,所以必须开启一个线程,再通过handle进行数据的提醒:
主要说明下, 在service中通过在oncreat()中开启一个线程,轮训ArrayList<AttachmentTask> 我这个附件下载的任务list ,ArrayList<AttachmentTask> 他维护的是一个当前下载的任务,每当下载完一个移除一个,同时下载完后添加到数据库。 不下载的时候,关掉该服务,现在该下载服务只是初版,有待进一步的优化,有什么好的建议可以留言:
转载请..:http://blog.csdn.net/liao3841054/article/details/7583003
- /*
- * @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;
- }
- }