Chinaunix首页 | 论坛 | 博客
  • 博客访问: 489348
  • 博文数量: 153
  • 博客积分: 3010
  • 博客等级: 中校
  • 技术积分: 1724
  • 用 户 组: 普通用户
  • 注册时间: 2008-12-08 11:55
文章分类

全部博文(153)

文章存档

2011年(1)

2010年(55)

2009年(88)

2008年(9)

我的朋友

分类: LINUX

2010-12-17 09:54:14



     8.FileService

package com.changcheng.download.service;

 

import java.util.HashMap;

import java.util.Map;

import android.content.Context;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

 

/**

 * 业务bean

 *

 */

public class FileService {

         private DBOpenHelper openHelper;

 

         public FileService(Context context) {

                   openHelper = new DBOpenHelper(context);

         }

         /**

          * 获取线程最后下载位置

          * @param path

          * @return

          */

         public Map getData(String path){

                   SQLiteDatabase db = openHelper.getReadableDatabase();

                   Cursor cursor = db.rawQuery("select threadid, position from filedown where downpath=?", new String[]{path});

                   Map data = new HashMap();

                   while(cursor.moveToNext()){

                            data.put(cursor.getInt(0), cursor.getInt(1));

                   }

                   cursor.close();

                   db.close();

                   return data;

         }

         /**

          * 保存下载线程初始位置

          * @param path

          * @param map

          */

         public void save(String path,  Map map){//int threadid, int position

                   SQLiteDatabase db = openHelper.getWritableDatabase();

                   db.beginTransaction();

                   try{

                            for(Map.Entry entry : map.entrySet()){

                                     db.execSQL("insert into filedown(downpath, threadid, position) values(?,?,?)",

                                                        new Object[]{path, entry.getKey(), entry.getValue()});

                            }

                            db.setTransactionSuccessful();

                   }finally{

                            db.endTransaction();

                   }

                   db.close();

         }

         /**

          * 实时更新线程的最后下载位置

          * @param path

          * @param map

          */

         public void update(String path, Map map){

                   SQLiteDatabase db = openHelper.getWritableDatabase();

                   db.beginTransaction();

                   try{

                            for(Map.Entry entry : map.entrySet()){

                                     db.execSQL("update filedown set position=? where downpath=? and threadid=?",

                                                        new Object[]{entry.getValue(), path, entry.getKey()});

                            }

                            db.setTransactionSuccessful();

                   }finally{

                            db.endTransaction();

                   }

                   db.close();

         }

         /**

          * 当文件下载完成后,清掉该文件对应的下载记录

          * @param path

          */

         public void delete(String path){

                   SQLiteDatabase db = openHelper.getWritableDatabase();

                   db.execSQL("delete from filedown where downpath=?", new Object[]{path});

                   db.close();

         }

        

}

 

       9.DownloadThread

package com.changcheng.net.download;

 

import java.io.InputStream;

import java.io.RandomAccessFile;

import java.net.HttpURLConnection;

import java.net.URL;

import android.util.Log;

 

public class DownloadThread extends Thread {

         private static final String TAG = "DownloadThread";

         private RandomAccessFile saveFile;

         private URL downUrl;

         private int block;

         /* 下载开始位置  */

         private int threadId = -1;

         private int startPos;

         private int downLength;

         private boolean finish = false;

         private FileDownloader downloader;

 

         public DownloadThread(FileDownloader downloader, URL downUrl, RandomAccessFile saveFile, int block, int startPos, int threadId) {

                   this.downUrl = downUrl;

                   this.saveFile = saveFile;

                   this.block = block;

                   this.startPos = startPos;

                   this.downloader = downloader;

                   this.threadId = threadId;

                   this.downLength = startPos - (block * (threadId - 1));

         }

        

         @Override

         public void run() {

                   if(downLength < block){//未下载完成

                            try {

                                      HttpURLConnection http = (HttpURLConnection) downUrl.openConnection();

                                     http.setRequestMethod("GET");

                                     http.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");

                                     http.setRequestProperty("Accept-Language", "zh-CN");

                                     http.setRequestProperty("Referer", downUrl.toString());

                                     http.setRequestProperty("Charset", "UTF-8");

                                     http.setRequestProperty("Range", "bytes=" + this.startPos + "-");

                                     http.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");

                                     http.setRequestProperty("Connection", "Keep-Alive");

                                    

                                     InputStream inStream = http.getInputStream();

                                     int max = block>1024 ? 1024 : (block>10 ? 10 : 1);

                                     byte[] buffer = new byte[max];

                                     int offset = 0;

                                     print("线程 " + this.threadId + "从位 置"+ this.startPos+ "开始下载 ");

                                     while (downLength < block && (offset = inStream.read(buffer, 0, max)) != -1) {

                                               saveFile.write(buffer, 0, offset);

                                               downLength += offset;

                                               downloader.update(this.threadId, block * (threadId - 1) + downLength);

                                               downloader.saveLogFile();

                                               downloader.append(offset);

                                               int spare = block-downLength;//求剩下的字节数

                                               if(spare < max) max = (int) spare;

                                     }

                                     saveFile.close();

                                     inStream.close();                   

                                     print("线程 " + this.threadId + "完成 下载 ");

                                     this.finish = true;

                                     this.interrupt();

                            } catch (Exception e) {

                                     this.downLength = -1;

                                     print("线程"+ this.threadId+ ":"+ e);

                            }

                   }

         }

         private static void print(String msg){

                   Log.i(TAG, msg);

         }

         /**

          * 下载是否完成

          * @return

          */

         public boolean isFinish() {

                   return finish;

         }

         /**

          * 已经下载的内容大小

          * @return 如果返回值为-1,代表下载失败

          */

         public long getDownLength() {

                   return downLength;

         }

}

 

       11.DBOpenHelper

package com.changcheng.download.service;

 

import android.content.Context;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

 

public class DBOpenHelper extends SQLiteOpenHelper {

         private static final String DBNAME = "download.db";

         private static final int VERSION = 2;

        

         public DBOpenHelper(Context context) {

                   super(context, DBNAME, null, VERSION);

         }

        

         @Override

         public void onCreate(SQLiteDatabase db) {

                   db.execSQL("CREATE TABLE IF NOT EXISTS filedown (id integer primary key autoincrement, downpath varchar(100), threadid INTEGER, position INTEGER)");

         }

 

         @Override

         public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

                   db.execSQL("DROP TABLE IF EXISTS filedown");

                   onCreate(db);

         }

}

 

       结束!



http://www.blogjava.net/changcheng/archive/2010/03/04/314515.html 
阅读(780) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2010-12-17 15:09:23

很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com