android 后台附件下载

  这近两天没有做什么事情,就做了一个下载管理的的功能, 写好供项目组中其他人员调用,复用我的下载功能。

  我们产品多处用到的下载附件功能, 同时支持的附件的管理: 查看,删除,转发

  点击下载的时候,显示下载的进度,当前有几个待下载的,完成了几个下载的,下载完的可以进行查看,删除,转发

   大家也知道,下载很耗时,所以我用了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

[java]  view plain copy
  1. /* 
  2.  * @project C6Client 
  3.  * @package com.jh.c6.service 
  4.  * @file DownloadService.java 
  5.  * @version  1.0 
  6.  * @author  liaoyp 
  7.  * @time  2012-5-17 上午2:55:19 
  8.  */  
  9. package com.jh.c6.service;  
  10.   
  11. import java.io.File;  
  12. import java.io.FileNotFoundException;  
  13. import java.io.FileOutputStream;  
  14. import java.io.IOException;  
  15. import java.io.InputStream;  
  16. import java.net.URL;  
  17. import java.net.URLConnection;  
  18. import java.util.ArrayList;  
  19. import java.util.List;  
  20.   
  21. import android.app.Notification;  
  22. import android.app.NotificationManager;  
  23. import android.app.PendingIntent;  
  24. import android.app.Service;  
  25. import android.content.Intent;  
  26. import android.os.Handler;  
  27. import android.os.IBinder;  
  28. import android.widget.Toast;  
  29.   
  30. import com.jh.c6.activity.C6ClientActivity;  
  31. import com.jh.c6.activity.DownloadMangerActivity;  
  32. import com.jh.c6.activity.R;  
  33. import com.jh.c6.entity.AttachmentTask;  
  34. import com.jh.c6.exception.POAException;  
  35. import com.jh.c6.impl.DownloadDB;  
  36. import com.jh.c6.util.Configure;  
  37.   
  38. public class DownloadService  extends Service implements Runnable{  
  39.       
  40.     private NotificationManager manager;  
  41.     private Notification notif;  
  42.     private Intent intent;  
  43.     Handler  handler = new Handler(){  
  44.         public void handleMessage(android.os.Message msg) {  
  45.             if(msg.what == 1){  
  46.                 Toast.makeText(getApplicationContext(), "该附件已下载"500).show();  
  47.                 startActivity();  
  48.             }else if(msg.what == 2){  
  49.                 startActivity();  
  50.                 Toast.makeText(getApplicationContext(), "该附件正在下载"500).show();  
  51.             }else if(msg.what == 3){  
  52. //              startActivity();  
  53.                 Toast.makeText(getApplicationContext(), "服务器不存在该附件!"500).show();  
  54.             }else{  
  55.                 manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);  
  56.                 Notification notification = new Notification(R.drawable.ic_launcher,"附件下载中",System.currentTimeMillis());  
  57.                 intent = new Intent();  
  58.                 intent.setClass(getApplicationContext(), DownloadMangerActivity.class);  
  59.                 intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NEW_TASK);  
  60.                   
  61.                 PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),  
  62.                         100, intent, PendingIntent.FLAG_UPDATE_CURRENT);  
  63.                 notification.setLatestEventInfo(getApplicationContext(), "附件下载""下载完成!", pendingIntent);  
  64.                 manager.notify(101, notification);  
  65.                 Toast.makeText(getApplicationContext(), "下载完成"500).show();  
  66.             }  
  67.               
  68.         };  
  69.     };  
  70.     //static LinkedList<AttachmentTask> attsTask = new LinkedList<AttachmentTask>();  
  71.      public static ArrayList<AttachmentTask> attsTask = new ArrayList<AttachmentTask>();  
  72.      public void  startActivity(){  
  73.             intent = new Intent();  
  74.             intent.setClass(getApplicationContext(), DownloadMangerActivity.class);  
  75.             intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NEW_TASK);  
  76.             DownloadService.this.startActivity(intent);  
  77.      }  
  78.     public  boolean isRun;  
  79.     public   final  static int  Max = 4;  
  80.     public  static boolean stopDownload;  
  81.       
  82.     static final Object NO_MORE_WORK = new Object();  
  83.   
  84.     private Thread t;  
  85.   
  86.     private DownloadDB downloadDB;  
  87.   
  88.     private Intent download;  
  89.     private File file;  
  90.       
  91.     @Override  
  92.     public IBinder onBind(Intent intent) {  
  93.         return null;  
  94.     }  
  95.     /** 
  96.      * 最大限制 
  97.      * @return 
  98.      */  
  99.     public static boolean  IsMaxNum (){  
  100.         return attsTask.size()>=Max? true:false;  
  101.     }  
  102.     /** 
  103.      * 任务列表中是否存在还任务 
  104.      * @param path 
  105.      * @return 
  106.      */  
  107.     public  static boolean isDownLoading(String path){  
  108.         for (int i = 0; i < attsTask.size(); i++) {  
  109.             if(attsTask.get(i).getUri().equals(path)){  
  110.                 return true;  
  111.             }  
  112.         }  
  113.         return false;  
  114.     }  
  115.     /** 
  116.      *  
  117.      * <code>getTask</code> 
  118.      * @description: TODO(获取附件总数)  
  119.      * @return 
  120.      * @since   2012-4-18    liaoyp 
  121.      */  
  122.     public static  int getTask(){  
  123.         if(UploadService.attsTask !=null)  
  124.         return attsTask.size();  
  125.         else   
  126.             return 0;  
  127.     }  
  128.     /** 
  129.      * 是否下载完成! 
  130.      * @return 
  131.      */  
  132.     public   static boolean   isDowloadFinshed(){  
  133.             for (int i = 0; i < attsTask.size(); i++) {  
  134.                     if(!attsTask.get(i).isOver()){  
  135.                             return false;  
  136.                     }  
  137.             }  
  138.             return true;  
  139.     }  
  140.     /** 
  141.      * 服务器地址 
  142.      * @return 
  143.      */  
  144.     public static List<String>  getDownloadServerPath(){  
  145.         List<String> atts = null;  
  146.         if(attsTask !=null && attsTask.size()>0){  
  147.              atts = new ArrayList<String>();  
  148.             for (int i = 0; i < attsTask.size(); i++) {  
  149.                 if(attsTask.get(i).isOver()){  
  150.                     atts.add(attsTask.get(i).getServerPath());  
  151.                 }  
  152.             }  
  153.             return atts;  
  154.         }  
  155.         return atts;  
  156.     }  
  157.       
  158.     @Override  
  159.     public void onCreate() {  
  160.         super.onCreate();  
  161.          isRun= true;  
  162.          t = new Thread(this);  
  163.          t.start();  
  164.     }  
  165.     @Override  
  166.     public void onStart(Intent intent, int startId) {  
  167.         // TODO Auto-generated method stub  
  168.         super.onStart(intent, startId);  
  169.         if(intent !=null &&intent.getExtras() !=null){  
  170.               
  171.             if(t == null){  
  172.                  t = new Thread(this);  
  173.                  t.start();  
  174.             }  
  175.           
  176.             String  uri = (String) intent.getExtras().get("uri");  
  177.             if(uri !=null){  
  178.                 for (int i = attsTask.size() -1; i >= 0; i--) {  
  179.                     if(attsTask.get(i).getUri().equals(uri)){  
  180.                         stopDownload = true;  
  181.                         attsTask.remove(i);  
  182.                         System.out.println("cancle ---->"+attsTask.size());  
  183.                         this.sendBroadcast(new Intent(C6ClientActivity.updateDowload));  
  184.                     }  
  185.                 }  
  186.             }  
  187.         }  
  188.           
  189.     }  
  190.       
  191.       
  192.     @Override  
  193.     public int onStartCommand(Intent intent, int flags, int startId) {  
  194.         return super.onStartCommand(intent, flags, startId);  
  195.     }  
  196.       
  197.     @Override  
  198.     public void run() {  
  199.         while(isRun)  
  200.         {  
  201.             try {  
  202.                 if (attsTask.size() > 0) {  
  203.                     for (int i = 0; i <attsTask.size(); i++) {  
  204.                         AttachmentTask task = attsTask.get(i);  
  205.                         if(! task.isUnSart()){  
  206.                             download(attsTask.get(i));  
  207.                         }  
  208.                     }  
  209.                 }   
  210.                 else {  
  211.                     try {  
  212.                         Thread.sleep(500);  
  213.                     } catch (Exception e) {  
  214.                     }  
  215.                 }  
  216.         }catch(Exception e){  
  217.             System.out.println("error-----------------"+e);  
  218.         }  
  219.         }  
  220.     }  
  221.     private void download(AttachmentTask task) throws POAException {  
  222.         // TODO Auto-generated method stub  
  223.         // 开始上传 和 更新下载的进度显示  
  224.         System.out.println("dowenload-----------------1");  
  225.         task.setUnSart(true);  
  226.         task.setSarting(true);  
  227.         if(downloadDB == null){  
  228.             downloadDB = new   DownloadDB();  
  229.         }  
  230.         String httpPath ;  
  231.         httpPath = task.getUri();  
  232.         String   loacalPath = downloadDB.getLocalpicPath(DownloadService.this, httpPath);  
  233.         System.out.println("localPath : "+loacalPath);  
  234.         if(loacalPath == null){  
  235.                 boolean b = isDownLoading(httpPath);  
  236.                 if(b){  
  237.                     // 发送广播通知  
  238.                     removeTask(task);  
  239.                     handler.sendEmptyMessage(2);  
  240.                 }else{  
  241.                     // 下载  
  242.                     startDowload(task);  
  243.                 }  
  244. //          Toast.makeText(getApplicationContext(), "开始下载", 500).show();  
  245.               
  246.             startDowload(task);  
  247.               
  248.         }else{  
  249.              File file = new File(loacalPath);  
  250.              if( ! file.exists()){  
  251.                   // 下载  
  252.                  startDowload(task);  
  253.              }else{  
  254.                  // 跳到附件管理界面  
  255.                 removeTask(task);  
  256.                  handler.sendEmptyMessage(1);  
  257.              }  
  258.         }  
  259.           
  260.     }  
  261.       
  262.     public void startDowload(AttachmentTask task){  
  263.         InputStream is = null;  
  264.         FileOutputStream fos = null;  
  265.         String httpPath = "";  
  266.         try {  
  267.             httpPath = (Configure.IPADDRESS.replaceAll("POSTServiceForAndroid.svc""")+"FileOutSteam.aspx?FileID="+  
  268.                     task.getUri());  
  269.             System.out.println("http: "+httpPath);  
  270.               
  271.             URLConnection  connetion = new URL(httpPath).openConnection();  
  272.              is=connetion.getInputStream();  
  273. //          HttpGet httpGet = new HttpGet(task.getUri());  
  274. //          HttpClient client = new DefaultHttpClient();  
  275. //          HttpParams httpParams = client.getParams();  
  276. //          HttpConnectionParams.setConnectionTimeout(httpParams,5000);  
  277. //          HttpConnectionParams.setSoTimeout(httpParams, 10000);  
  278. //          HttpResponse httpResponse = client.execute(httpGet);  
  279.   
  280. //          if (httpResponse.getStatusLine().getStatusCode() == 200) {  
  281. //  
  282. //               is = httpResponse.getEntity().getContent();  
  283.   
  284.                 // 开始下载apk文件  
  285.                  String path =  Configure.DATADIR+Configure.DownloadFile + "/"+task.getServerPath();  
  286.                  file = new File(path);  
  287.                   if( ! file.exists()){  
  288.                       file.createNewFile();  
  289.                   }  
  290.                  fos = new FileOutputStream(file);  
  291.   
  292.                 byte[] buffer = new byte[2048];  
  293.                 int count = 0;  
  294.                 while ((count = is.read(buffer)) != -1) {  
  295.                     if (stopDownload) {  
  296.                          break ;  
  297.                     }  
  298.                     fos.write(buffer, 0, count);  
  299.                   
  300.                     // 进行进度跟新  
  301.                     long  current= task.getCurrentProgress();  
  302.                     current =task.getCurrentProgress() +count;  
  303.                     task.setCurrentProgress(current);  
  304.                       
  305.                     // send broadCast  to mangeAttachmengActivity  
  306.                     download = new Intent(C6ClientActivity.DowloadAction);  
  307.                     download.putExtra("type"0);  
  308.                     this.sendBroadcast(download);  
  309.                     System.out.println("下载中......");  
  310.                 }  
  311.                 fos.flush();  
  312.                 removeTask(task);  
  313.                 if(downloadDB != null){  
  314.                     downloadDB.insertPic(DownloadService.this, task.getUri(),path, Configure.ACCOUNTID);  
  315.                 }else{  
  316.                     new DownloadDB().insertPic(DownloadService.this, task.getUri(),path, Configure.ACCOUNTID);  
  317.                 }  
  318.                 //  提示下载完成 !  
  319. //              download = new Intent(C6ClientActivity.DowloadAction);  
  320. //              download.putExtra("type", 1);  
  321. //              this.sendBroadcast(download);  
  322.                 handler.sendEmptyMessage(0);  
  323.             }catch (FileNotFoundException e) {  
  324.                 e.printStackTrace();  
  325.                 handler.sendEmptyMessage(3);  
  326.             }catch (IOException e) {  
  327.                 e.printStackTrace();  
  328.             } finally{  
  329.                 try {  
  330.                     if (fos != null) {  
  331.                         fos.close();  
  332.                     }  
  333.                 } catch (IOException e) {  
  334.                     e.printStackTrace();  
  335.                 }  
  336.                 try {  
  337.                     if (is != null) {  
  338.                          is.close();  
  339.                     }  
  340.                 } catch (IOException e) {  
  341.                     e.printStackTrace();  
  342.                 }  
  343.             }  
  344.     }  
  345.       
  346.       
  347.     public static  void removeTask(AttachmentTask task){  
  348.         if(attsTask.contains(task)){  
  349.             attsTask.remove(task);  
  350.         }  
  351.     }  
  352.     public static  void  addTask(AttachmentTask task){  
  353.         stopDownload = false;  
  354.         attsTask.add(task);  
  355.     }  
  356.   
  357.     @Override  
  358.     public void onDestroy() {  
  359.         super.onDestroy();  
  360.         isRun = false;  
  361.     }  

  1.     }  
原文出处:http://blog.csdn.net/liaoyp_ios_android/article/details/7583003

猜你喜欢

转载自blog.csdn.net/xuhui_7810/article/details/38734281