断点续传

思路:
1.暂停时,停止下载线程,记录下载进度。
2.恢复时,启动新下载进程,判断下载进度。

package com.eee168.upgrade.updateclient.task;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import android.util.Log;
import com.eee168.upgrade.updateclient.engine.EngineServer;
import com.eee168.upgrade.updateclient.service.UpdateServiceListener;
import com.eee168.upgrade.updateclient.update.UpdateItem;
import com.eee168.upgrade.updateclient.update.UpdateList;
import com.eee168.upgrade.updateclient.update.UpdateListListener;
import com.eee168.upgrade.updateclient.updatecheck.IUpdateCheckTimer;
import com.eee168.upgrade.updateclient.updatecheck.UpdateCheckTimer;
import com.eee168.upgrade.updateclient.util.EventHandler;
import com.eee168.upgrade.updateclient.util.UpdateUtils;

public class DownLoadEngine implements IDownLoadTaskListener,IUpdateCheckTimer{
	private static final String TAG = "DownLoadEngine";
	private List<DownloadUpdateTask> downLoadingTaskList = new ArrayList<DownloadUpdateTask>();
	private UpdateList iDownLoadingDB = null;
	private EngineServer engineServer;
	private UpdateListListener 		listener = null;
	private UpdateServiceListener 	servicelistener = null;
	private ArrayList<UpdateItem>  itemList = null;
	
    private UpdateCheckTimer mRetryTimer = null;
    private int retryTime = 0;
    
	public DownLoadEngine(){
		engineServer = EngineServer.getInstance();
	}
	
	public void InitDownLoadingTaskList(UpdateList item)
	{
		if(item != null){
			iDownLoadingDB = item;
		}else if(iDownLoadingDB == null){
			iDownLoadingDB = new UpdateList(engineServer.getContext(),engineServer.getCursor());
		}
		itemList =  iDownLoadingDB.getList();
		
		if (itemList.size()<=0)
		{
			return;
		}

		for(int i = 0;i<itemList.size();i++)
		{
			if(itemList.get(i).getStatus()!=UpdateItem.FINISHED)
			{
				DownloadUpdateTask aItem = new DownloadUpdateTask(this,itemList.get(i));
				downLoadingTaskList.add(aItem);
			}
			
		}

	}
	

	
	public int getDBItemListCount(){
		return iDownLoadingDB.getList().size();
	}
	
	public UpdateListListener getListener() {
		return listener;
	}

	public void setListener(UpdateListListener listener) {
		this.listener = listener;
	}
	
	public UpdateServiceListener getServicelistener() {
		return servicelistener;
	}

	public void setServicelistener(UpdateServiceListener servicelistener) {
		this.servicelistener = servicelistener;
	}

	public List<DownloadUpdateTask> getDownLoadingTaskList() {
		return downLoadingTaskList;
	}

	public void setDownLoadingTaskList(List<DownloadUpdateTask> downLoadingTaskList) {
		this.downLoadingTaskList = downLoadingTaskList;
	}

	public int startDownloadTask(){
		if(iDownLoadingDB!=null){
			itemList =  iDownLoadingDB.getList();
	        if (itemList.isEmpty()) {
	            return -1;
	        }
	        // first set all items status to wait
	        Iterator<UpdateItem> it = itemList.iterator();
	        while (it.hasNext()) {
	        	UpdateItem nextItem = it.next();

	            if (nextItem.getStatus() != UpdateItem.FINISHED){
	            	if(startDownloadTask((int)nextItem.getItemId()-1)){
	            		nextItem.setStatus(UpdateItem.RUNNING);
	            		engineServer.setTaskRunning(true);
	            		return 0;
	            	}else{
	            		return -1;
	            	}
	            }
	        }
			return 0;
		}
			return -1;

	}
	
	public boolean startDownloadTask(int index){
		itemList =  iDownLoadingDB.getList();
		if(downLoadingTaskList.size()>0&&downLoadingTaskList.size()>index){
			DownloadUpdateTask task = downLoadingTaskList.get(index);
				if(!task.isTaskRunning()){
					task.Start();
					engineServer.setTaskRunning(true);
					servicelistener.taskStarted(itemList.get(index));
					return true;
			}
		}else{
			
			if(itemList.size()>0&&itemList.size()>index){
				UpdateItem item = itemList.get(index);
				DownloadUpdateTask task = new DownloadUpdateTask(this,item);
				downLoadingTaskList.add(task);
				task.Start();
				engineServer.setTaskRunning(true);
				servicelistener.taskStarted(itemList.get(index));
				return true;
			}

		}
		
		return false;
	}
	
	public DownloadUpdateTask addDownLoadTask(UpdateItem item){
		iDownLoadingDB.addItem(item);
		DownloadUpdateTask task = new DownloadUpdateTask(this,item);
		downLoadingTaskList.add(task);
		return task;
	}
	
	public DownloadUpdateTask continueTask(int index){
		Log.d(TAG, "continueTask function,downloadingTaskList.size : ["+downLoadingTaskList.size()+"]");
		Log.d(TAG, "continueTask function,parameters index : ["+index+"]");
		while(downLoadingTaskList.size()>0)
			downLoadingTaskList.remove(0);
		itemList =  iDownLoadingDB.getList();
		UpdateItem item = itemList.get(index);
		DownloadUpdateTask task = new DownloadUpdateTask(this,item);
		downLoadingTaskList.add(task);
		task.Start();
		engineServer.setTaskRunning(true);
		servicelistener.taskStarted(itemList.get(index));
//		/*this is judge show switch button text*/
//		new MainActivity().judgeShowSwitchButton();
		//startDownloadTask();
		return task;
	}
	public boolean pauseDownloadTask(int index){
		itemList =  iDownLoadingDB.getList();
		if(itemList.size()<=index) return false;
		UpdateItem item = itemList.get(index);
        item.setStatus(UpdateItem.PAUSED);
		iDownLoadingDB.updateItem(item);
		if(listener!=null)
			listener.UpdateListChanged(UpdateList.DOWNLOAD_LIST_EVNET_UPDATE_ITEM, item);
		if(downLoadingTaskList.size()>0)
			downLoadingTaskList.remove(0);
       // removeTask(aId);
		engineServer.setTaskRunning(false);
		if(servicelistener!=null)
			servicelistener.taskCancel(item);
		return false;
	}
	
	public boolean deleteDownloadTask(int index){
		itemList =  iDownLoadingDB.getList();
		if(itemList.size()<=index) return false;
		UpdateItem item = itemList.get(index);
		if(iDownLoadingDB.removeItem(item.getItemId())){
			if(downLoadingTaskList.size()>0)
				downLoadingTaskList.remove(index);
			//removeTask(aId);
			engineServer.setTaskRunning(false);
			engineServer.setUpDateTaskType(EngineServer.TASKNULL);
			UpdateUtils.DeleteFile(UpdateUtils.DOWNLOAD_FILE_NAME);
			UpdateUtils.DeleteFile(UpdateUtils.DOWNLOAD_FILE_NAME+".part");
		}
		if(listener!=null)
			listener.UpdateListChanged(UpdateList.DOWNLOAD_LIST_EVNET_REMOVE_ITEM, item);
		if(servicelistener!=null)
			servicelistener.taskDelete(item);
		return true;
	}
	
	public void deleteAllTask(){
		itemList =  iDownLoadingDB.getList();
		iDownLoadingDB.removeItems(itemList);
		while(downLoadingTaskList.size()>0){
			downLoadingTaskList.remove(0);
		}
		engineServer.setTaskRunning(false);
		engineServer.setUpDateTaskType(EngineServer.TASKNULL);
		UpdateUtils.DeleteFile(UpdateUtils.DOWNLOAD_FILE_NAME);
		UpdateUtils.DeleteFile(UpdateUtils.DOWNLOAD_FILE_NAME+".part");

	}

	private boolean removeTask(int index){
		if(downLoadingTaskList.size()<=index||0>index)
			return false;
        DownloadUpdateTask task = downLoadingTaskList.get(index);
        	task.cancel(true);
      
      	downLoadingTaskList.remove(index);
		engineServer.setTaskRunning(false);
		engineServer.setUpDateTaskType(EngineServer.TASKNULL);
      	return true;
	}
	
	private boolean  retryTask(int index){
		Log.d(TAG, "--retryTask function,continue task when onDownloadEvent if type equals EventHandler.TASKFAILED--");
		Log.d(TAG, "--retryTask function,downloadingTaskList.size:"+downLoadingTaskList.size()+"--");
		if(downLoadingTaskList.size()<=index||index<0)
			return false;
        DownloadUpdateTask task = downLoadingTaskList.get(index);
        task.cancel(true);
        downLoadingTaskList.remove(index);
        continueTask(index);
        Log.i(TAG, "DownLoadEngine -------> retryTask time = "+String.valueOf(retryTime));
      	return true;
	}
	
	public boolean OnDownLoadEvent(int aEnevtType, UpdateItem aItem, long aResutlt) {
		// TODO Auto-generated method stub
		itemList = iDownLoadingDB.getList();
//		if(itemList.size()<=0||itemList.size()<aId)
//			return false;
		
        UpdateItem item = aItem;

		switch (aEnevtType) {
		case EventHandler.TASKCOMPLETED: 
		{
	        item.setStatus(UpdateItem.FINISHED);
	        try {
	        	iDownLoadingDB.updateItem(item);
	        } catch (Exception e) {
	        	Log.i(TAG, "Update file taskCompleted()  err =====> "+e.toString());
	            //e.printStackTrace();
	        	engineServer.setTaskRunning(false);
	        }
	        if(listener!=null)
				listener.UpdateListChanged(UpdateList.DOWNLOAD_LIST_EVNET_UPDATE_ITEM, item);
	        servicelistener.taskCompleted(item);
	        engineServer.setTaskRunning(false);
	        engineServer.setUpDateTaskType(EngineServer.TASKNULL);

	        //removeTask(aId);
	        if(downLoadingTaskList.size()>0)
	        	downLoadingTaskList.remove(0);
			break;
		}
		case EventHandler.TASKMAXSIZE:
		{
			item.setStatus(UpdateItem.RUNNING);
	        item.setFileSize(aResutlt);
			iDownLoadingDB.updateItem(item);

			if(listener!=null)
				listener.UpdateListChanged(UpdateList.DOWNLOAD_LIST_EVNET_UPDATE_ITEM, item);
			break;
		}
		case EventHandler.TASKPROGRESS:
		{
	        item.setStatus(UpdateItem.RUNNING);
	        item.setDownloadSize(aResutlt);
			iDownLoadingDB.updateItem(item);
			if(listener!=null)
				listener.UpdateListChanged(UpdateList.DOWNLOAD_LIST_EVNET_UPDATE_ITEM, item);
			break;
		}
		case EventHandler.TASKCANCEL: 
		{
			//deleteDownloadTask(0);
			deleteAllTask();
			if(listener!=null)
				listener.UpdateListChanged(UpdateList.DOWNLOAD_LIST_EVNET_REMOVE_ITEM, null);
			if(servicelistener!=null)
				servicelistener.taskDelete(null);
			break;
		}
		case EventHandler.TASKFAILED:
		{
			if(UpdateUtils.isStopTask()){
				retryTime = 5;
			}
			if(retryTime < 5){
		        item.setStatus(UpdateItem.WAITING_HIGH);
				iDownLoadingDB.updateItem(item);
				if(listener!=null)
					listener.UpdateListChanged(UpdateList.DOWNLOAD_LIST_EVNET_UPDATE_ITEM, item);
				retryTask(0);
		        retryTime++;
			}else{
		        item.setStatus(UpdateItem.FAILED);
		        //item.setDownloadSize(aResutlt);
				iDownLoadingDB.updateItem(item);
				if(listener!=null)
					listener.UpdateListChanged(UpdateList.DOWNLOAD_LIST_EVNET_UPDATE_ITEM, item);
				
				engineServer.setTaskRunning(false);
				engineServer.setUpDateTaskType(EngineServer.TASKNULL);
				//removeTask(aId);
				if(downLoadingTaskList.size()>0)
					downLoadingTaskList.remove(0);

				if(servicelistener!=null)
					servicelistener.taskCancel(item);
				
				retryTime = 0;
			}

			break;
		}
		case EventHandler.TASKPAUSE:
		{
			pauseDownloadTask(0);
			break;
		}
		case EventHandler.TASKNOENOUGHSPACE:
		{
		        item.setStatus(UpdateItem.FAILED);
				iDownLoadingDB.updateItem(item);
				engineServer.setTaskRunning(false);
				engineServer.setUpDateTaskType(EngineServer.TASKNULL);
				if(downLoadingTaskList.size()>0)
					downLoadingTaskList.remove(0);
				if(listener!=null)
					listener.UpdateListChanged(UpdateList.DOWNLOAD_LIST_EVNET_UPDATE_ITEM, item);
				if(servicelistener!=null)
					servicelistener.taskErrNoSpace();

			break;
		}
			
		}
		return true;
	}

	public void OnNotifyTimer(UpdateCheckTimer aSelf) {
		// TODO Auto-generated method stub
		if(retryTime<5){
			retryTime++;
			
			if(UpdateUtils.DEBUG) Log.i(TAG, "DownLoadEngine ------>>>>>>>>>OnNotifyTimer  ===="+retryTime);
		}else{
			cancelRetryTimer();
			if(UpdateUtils.DEBUG) Log.i(TAG, "DownLoadEngine ----->>>>>>>>>cancelRetryTimer");
		}
	}

	private void startRetryTimer(){
		if(mRetryTimer == null){
			mRetryTimer = new UpdateCheckTimer(this);
		}
		if(!mRetryTimer.isiIsRun())
			mRetryTimer.Start(1000*10,1000*5);
		if(UpdateUtils.DEBUG)
			Log.i(TAG, "DownLoadEngine ----> startRetryTimer");
	}
	
	private void cancelRetryTimer(){
		if(mRetryTimer!=null&&mRetryTimer.isiIsRun()){
			mRetryTimer.Cancel();
			mRetryTimer = null;
		}
	}
}


package com.eee168.upgrade.updateclient.task;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URI;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Process;
import android.os.SystemClock;
import android.util.Log;

import com.eee168.upgrade.updateclient.update.UpdateItem;
import com.eee168.upgrade.updateclient.util.EventHandler;
import com.eee168.upgrade.updateclient.util.UpdateUtils;

public class DownloadUpdateTask extends AsyncTask<UpdateItem, Integer, File> {
    //public static DownloadUpdateTask INSTANCE;

    private static final String TAG = "DownloadUpdateTask";
    public static final String KEY_UPDATE_INFO = "updateInfo";
    
    private static final int CONNECTION_TIMEOUT = 30000;
    //private ProgressBar mProgressBar;
    private IDownLoadTaskListener mListener;
    
    private HttpClient mHttpClient;
    private	HttpUriRequest req;
    private File mDestinationFile;
    private File mDestinationMD5File;
    //private boolean pbLenghtSet;
    private UpdateItem mItem;
 
    private long iStartPos;
    
    private RandomAccessFile iFileHand = null;
    private boolean isTaskRunning = false;
    
//    private final int STATE_Completed = 100;
//    private final int STATE_Delete = 200;
//    private final int STATE_Pause = 300;
//    private final int STATE_NOSPACE = 400;
//    private final int STATE_ERR = 500;
    private int mState = 0;
    
    /**
     * this is double parameters structure methods
     * 
     * this is update client ,download update.zip task
     * 
     * @param listener this is a download event listener ,
     * @param aItem this is update item ,it contains upgrade news and a little parameters
     */
    public DownloadUpdateTask(IDownLoadTaskListener listener,UpdateItem aItem) {
        //if(INSTANCE != null) throw new RuntimeException("Another instance of " + TAG + " is already running");
       // INSTANCE = this;
        mItem = aItem;
        setDownLoadTaskListener(listener);

        mHttpClient = new DefaultHttpClient(createHttpParams());

        String destFileName = aItem.getDisplayFileName()+UpdateUtils.DOWNLOAD_FILENAME_SUFFIX;
        mDestinationFile = new File(UpdateUtils.DOWNLOAD_FILE_PATH, destFileName);
        iStartPos = mItem.getDownloadSize();
        
        if(iStartPos == 0){
        	String filename = aItem.getFileName()+".part";
        	UpdateUtils.DeleteFile(filename);
        }else{
            if(mDestinationFile.exists()){
            	if(mDestinationFile.length()!=mItem.getDownloadSize()){
            		mItem.setDownloadSize(mDestinationFile.length());
            		iStartPos = mDestinationFile.length();
            	}
            }
        }
        
        InitialFile();
    }
    
	private void sendBroadcast(Context context,String what,String name, int value){
		Intent i = new Intent(what);
		i.putExtra(name, value);
		if(context != null){
			context.sendBroadcast(i);
		}
		
	}
    
    /**
     * this is AsyncTask , run in the background
     */
    public File doInBackground(UpdateItem ... items) {
    	
		Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);

		mItem = items[0];

		File destinationFile = mDestinationFile;
		HttpClient httpClient = mHttpClient;
		HttpResponse response = null;
		iStartPos = mItem.getDownloadSize();
		
		int flag = InitialFile();
		if(flag != 0){
        	sendBroadcast(UpdateUtils.getMainActivityContext(), EventHandler.UPDATE_DOWNLOAD_TASK_LOCAL_DAMAGE, EventHandler.UPDATE_DOWNLOAD_TASK_LOCAL_DAMAGE_TYPE, flag);
        } else {
		URI updateURI = URI.create(mItem.getUrl());

		setTaskRunning(true);
		try {
			req = new HttpGet(updateURI);
			if(iStartPos > 0)
			{
				req.addHeader("RANGE", "bytes=" + String.valueOf(iStartPos) + "-");
			}
			response = httpClient.execute(req);
			int serverResponse = response.getStatusLine().getStatusCode();
			if(req.isAborted() == true){
				 return null;
			}
			if(serverResponse == HttpStatus.SC_NOT_FOUND){
				if (UpdateUtils.DEBUG) Log.d(TAG, "File not found on Server. Trying next one.");
				if(mState == 0) mState = EventHandler.TASKFAILED;
			}else if (serverResponse == HttpStatus.SC_OK||serverResponse == HttpStatus.SC_PARTIAL_CONTENT){
				//dumpFile(response.getEntity(), destinationFile);
				HttpEntity entity = response.getEntity();
				long contentLength = entity.getContentLength();
				if (contentLength < 0){
					if (UpdateUtils.DEBUG) Log.w(TAG, "unable to determine the update file size");
				}else{
					if (UpdateUtils.DEBUG) Log.i(TAG, "Update size: " + (contentLength / 1024) + "KB");
	
					/*
					if(!SysUtils.EnoughSpaceOnSdCard(contentLength)){
						if(mItem.getFileSize()<=0){
							mItem.setFileSize(contentLength);
						}
						mState = EventHandler.TASKNOENOUGHSPACE;
						return null;
					}
					*/
					
					if(mItem.getFileSize()<=0)
						mListener.OnDownLoadEvent(EventHandler.TASKMAXSIZE, mItem, contentLength);
				}
				
				byte[] buff = new byte[4 * 1024];
				int read = 0;
				int totalDownloaded = (int)iStartPos;
				long aStartClock = SystemClock.elapsedRealtime();
				
				InputStream is = entity.getContent();
				if(is!=null){
					while (!Thread.currentThread().isInterrupted()&& (read = is.read(buff)) != -1) {
						
						iFileHand.write(buff, 0, read);
						totalDownloaded += read;
						long aCurClock = SystemClock.elapsedRealtime();
						if(aCurClock - aStartClock > 1000){
							
							if(mState != EventHandler.TASKCANCEL&&mState != EventHandler.TASKPAUSE)
								publishProgress(mItem.getItemId()-1, totalDownloaded);
							
								aStartClock = aCurClock;
						}
						mItem.setDownloadSize(totalDownloaded);
					}
					if(req.isAborted() == true){
						 return null;
					}
					if (read > 0) {
						throw new IOException("Download Canceled");
					}
				}
				
				if(req.isAborted() == true){
					 return null;
				}
				int statusCode = response.getStatusLine().getStatusCode();
				if(statusCode >= 200 && statusCode < 300){
					mState = EventHandler.TASKCOMPLETED;
					return destinationFile;
				}
				
			} else {
				Log.e(TAG, "Server returned status code  == " + serverResponse+ " trying next mirror");
				if(mState == 0) mState = EventHandler.TASKFAILED;
			}
		}catch (SocketException e){
			if(mState == 0)mState = EventHandler.TASKFAILED;
		}catch(SocketTimeoutException ee){
			if(mState == 0)mState = EventHandler.TASKFAILED;
		}catch (IOException ex){
			Log.w(TAG,"An error occured while downloading the update file. Trying next mirror",ex);
			if(mState == 0)mState = EventHandler.TASKFAILED;
		}catch (Exception ex) {
			Log.w(TAG,"An error occured while downloading the update file. Trying next mirror",ex);
			if(mState == 0) mState = EventHandler.TASKFAILED;
			return null;
		}finally{
//			if(mHttpClient!=null)
//				mHttpClient.getConnectionManager().shutdown();
		}
		if (Thread.currentThread().isInterrupted()||!Thread.currentThread().isAlive())
			return null;

		Log.e(TAG, "Unable to download the update file from any mirror");

      }
       return null;
    }

    
    public void onProgressUpdate(Integer... values) {
            if(mListener!=null)
            	mListener.OnDownLoadEvent(EventHandler.TASKPROGRESS, mItem,values[1]);
            
            //lcoalFileSize because the contentLength will only be the missing bytes and not the whole file
//            long contentLengthOfFullDownload = mcontentLength + localFileSize;
//            long speed = ((mtotalDownloaded - localFileSize) / (System.currentTimeMillis() - mStartTime));
//            speed = (speed > 0) ? speed : 1;
//            long remainingTime = ((contentLengthOfFullDownload - mtotalDownloaded) / speed);
//            String stringDownloaded = mtotalDownloaded / 1048576 + "/" + contentLengthOfFullDownload / 1048576 + " MB";
//            String stringSpeed = speed + " kB/s";
//            String stringRemainingTime = remainingTime / 60000 + " " + minutesString + " " + remainingTime % 60 + " " + secondsString;
//            String stringComplete = stringDownloaded + " " + stringSpeed + " " + stringRemainingTime;
            
    }

    
    public void onPostExecute(File result) {
            //INSTANCE = null;
            try {
            	if(iFileHand!=null)
            		iFileHand.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			doHandleErr(mState);
			//mListener.OnDownLoadEvent(mState, mItem,0);
    }


	private void dumpFile(HttpEntity entity, File destinationFile)throws IOException {
			long contentLength = entity.getContentLength();
			if (contentLength < 0)
				Log.w(TAG, "unable to determine the update file size");
			else{
				Log.i(TAG, "Update size: " + (contentLength / 1024) + "KB");
				if(mItem.getFileSize()<=0)
					mListener.OnDownLoadEvent(EventHandler.TASKMAXSIZE, mItem, contentLength);
			}
			
			long aStartClock = SystemClock.elapsedRealtime();
			byte[] buff = new byte[4 * 1024];
			int read = 0;
			int totalDownloaded = (int)iStartPos;

			InputStream is = entity.getContent();
			try {
			if(is!=null){
				while (!Thread.currentThread().isInterrupted()&& (read = is.read(buff)) != -1) {
					
					iFileHand.write(buff, 0, read);
					totalDownloaded += read;
					long aCurClock = SystemClock.elapsedRealtime();
					if(aCurClock - aStartClock > 1000){
						
							publishProgress(mItem.getItemId()-1, totalDownloaded);
						
							aStartClock = aCurClock;
					}
					
				}
				if(req.isAborted() == true){
					 return ;
				}
				if (read > 0) {
					throw new IOException("Download Canceled");
				}
			}

		} finally {
			if (is != null)
				is.close();
			if (entity != null) {
				try {
					entity.consumeContent();
				} catch (IOException e) {

				}
			}

		}
	}

	private void doHandleErr(int aState){
		switch(aState){
		case EventHandler.TASKCOMPLETED:{
			mListener.OnDownLoadEvent(EventHandler.TASKCOMPLETED, mItem,0);
			break;
		}
		case EventHandler.TASKCANCEL:{
			if(mListener!=null)
				 mListener.OnDownLoadEvent(EventHandler.TASKCANCEL, mItem,0);
			break;
		}
		case EventHandler.TASKPAUSE:{
			if(mListener!=null)
				 mListener.OnDownLoadEvent(EventHandler.TASKPAUSE, mItem,0);
			break;
		}
		case EventHandler.TASKFAILED:{
			if(mListener!=null)
				mListener.OnDownLoadEvent(EventHandler.TASKFAILED, mItem,0);

			break;
		}
		case EventHandler.TASKERR:{
			if(mListener!=null)
				 mListener.OnDownLoadEvent(EventHandler.TASKERR, mItem,0);
			break;
		}
		case EventHandler.TASKNOENOUGHSPACE:{
			if(mListener!=null)
				mListener.OnDownLoadEvent(EventHandler.TASKNOENOUGHSPACE, mItem, 0);
			break;
		}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#finalize()
	 */
	@Override
	protected void finalize() throws Throwable {
		cancel(true);
	}
	
    void setDownLoadTaskListener(IDownLoadTaskListener aListener){
    	mListener = aListener;
    }
    
    /**
     * this is start task function ,AsyncTask
     */
	public void Start() {
		try {
			execute(mItem);
			setTaskRunning(true);
			if (UpdateUtils.DEBUG) 
				Log.e(TAG, "url === "+mItem.getUrl());
		} catch (Exception e) {
			setTaskRunning(false);
		}
	}
	

	
	public void Abort()
	{
		if(req != null)
		{
			req.abort();
			//onCancelled();
		}
	}
	
	public void delete()
	{
		mState = EventHandler.TASKCANCEL;
		Abort();
		//cancel(true);
//		if(mListener!=null)
//        	mListener.OnDownLoadEvent(EventHandler.TASKCANCEL, mItem.getItemId()-1,0);
	}
	
	public void pauseTask(){
		mState = EventHandler.TASKPAUSE;
		Abort();
//		if(mListener!=null)
//        	mListener.OnDownLoadEvent(EventHandler.TASKPAUSE, mItem.getItemId()-1,0);
	}
	
	public int InitialFile() {
		int err = -1;
		try {
			if(iFileHand == null){
				iFileHand = new RandomAccessFile(mDestinationFile, "rwd");
				Log.d(TAG, "init RandomAccessFile ,iFileHand : ["+iFileHand+"]");
			}
			
			if (iFileHand == null){
				Log.d(TAG, "init RandomAccessFile error ,iFileHand : ["+iFileHand+"]");
				return -1;
			}
				
			if (iStartPos > 0) {
				iFileHand.seek(iStartPos);
			}
			return 0;
		} catch (Exception e) {
			Log.d(TAG, "init RandomAccessFile error : ["+e.toString()+"]");
			return -2;
		}
	}

	public boolean isTaskRunning() {
		return isTaskRunning;
	}

	public void setTaskRunning(boolean isTaskRunning) {
		this.isTaskRunning = isTaskRunning;
	}
	
	public UpdateItem getmItem() {
		return mItem;
	}
	public void setmItem(UpdateItem mItem) {
		this.mItem = mItem;
	}
	
    /**
     * Create the default HTTP protocol parameters.
     */
    private HttpParams createHttpParams() {
        final HttpParams params = new BasicHttpParams();

        // Turn off stale checking. Our connections break all the time anyway,
        // and it's not worth it to pay the penalty of checking every time.
        HttpConnectionParams.setStaleCheckingEnabled(params, false);
        HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params,CONNECTION_TIMEOUT);
        HttpClientParams.setRedirecting(params, false);
        
        return params;
    }
	
}


/////end file

你可能感兴趣的:(断点续传)