当前位置: 代码迷 >> Java相关 >> 乞援 AsyncTask 正解
  详细解决方案

乞援 AsyncTask 正解

热度:6585   发布时间:2013-02-25 21:51:41.0
求助 AsyncTask 正解
protected String doInBackground(String... aurl) 
{
// check the storage media size
File file = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(file.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
sdcardSize = blockSize*availableBlocks;
InputStream input = null;
OutputStream output = null;
try 
{
// create connection
URL conn = new URL(aurl[0]);
HttpURLConnection httpConn = (HttpURLConnection)conn.openConnection();
httpConn.setConnectTimeout(20*1000);
httpConn.setReadTimeout(20*1000);
//httpConn.connect();

if(httpConn.getResponseCode()==200)
{
// get update.zip size
updateSize = httpConn.getContentLength();
Log.i(TAG,"updateSize:"+updateSize);
if(updateSize>sdcardSize)
{
downResult = STORAGE_MEDIA_RESULT;
return downResult;
}
else
{
downResult = DOWNLOAD_FINISH;
// create InputStream
input = new BufferedInputStream(conn.openStream());
// create OutputStream
output = new FileOutputStream(FILEPATH);
byte[] data = new byte[1024];
// create Thread
Thread thread = new Thread(DownLoadFileAsync.this);
thread.start();
// write update.zip to sdcard
while((count=input.read(data))!=-1)
{
total += count;
output.write(data,0,count);
}
}
}
else if(httpConn.getResponseCode()==404)
{
downResult = INVALIDATED_RUL_RESULT;
return downResult;
}
}
catch (Exception e) 
{
downResult = DOWNLOAD_FAIL_RESULT;
Log.i(TAG,e.getMessage().toString());
}
finally
{
try
{
if(output!=null)
{
output.flush();
output.close();
input.close();
}

catch (IOException e) 
{
e.printStackTrace();
}
 
}
return downResult;
}  

问题 当下载的过程中如果网络断开或服务器无响应会一直等待 求解决办法 如果可以的话 给出可以继续/暂停下载的方法 谢谢

------解决方案--------------------------------------------------------
先了解 HTTP 协议中客户端请求的 Range 头和服务端响应的 Content-Range 头,之后我想你就应该知道怎么做了。