android 後臺附件下載

 在service中通過在oncreat()中開啓一個線程,輪訓ArrayList<AttachmentTask> 我這個附件下載的任務list ,ArrayList<AttachmentTask> 他維護的是一個當前下載的任務,每當下載完一個移除一個,同時下載完後添加到數據庫。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
/*
 * @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;
    }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章