3
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.AsyncTask;
import android.util.Log;
public class IssueDownload extends AsyncTask<IRPack, Void, IRPack> {
public static final String TAG = "IssueDownload";
public String path = null;
public IRIssue issue = null;
@Override
protected IRPack doInBackground(IRPack... parms) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
issue = Broker.model.issueDataStore.getIRIssue(parms[0].pubKey);
try {
File downloadFile = new File(IRConstant.issueFolder(issue.year, issue.month, issue.day, issue.pubKey) + "/" + parms[0].currPage + ".zip");
if (!downloadFile.exists()) {
path = IRConstant.downloadFile(issue.year, issue.month, issue.day, issue.pubKey, "content", ""
+ parms[0].currPage);
URL url = new URL(path);
Log.d (TAG,"input: " + path);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
return null;
// return "Server returned HTTP " + connection.getResponseCode()
// + " " + connection.getResponseMessage();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(IRConstant.issueFolder(issue.year, issue.month, issue.day, issue.pubKey) + "/" + parms[0].currPage + ".zip");
Log.d (TAG,"output: " + output);
byte data[] = new byte[1024];
int count;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
}
} catch (Exception e) {
// return e.toString();
return null;
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return parms[0];
}
@Override
protected void onPostExecute(IRPack pack) {
// TODO Auto-generated method stub
super.onPostExecute(pack);
pack.downloadPackComplete(); // Unzip completed pack
}
}
我目前正在使用此下載類,如果連接失敗,重試連接,如果重試2次後連接失敗,請重新連接。謝謝當連接丟失時異步任務下載器將失敗
謝謝,我已經使用try catch來敬酒的警告,但是,我該怎麼處理如果用戶再次連接?謝謝 – user782104
您可以設置廣播接收器來接收連接重新建立事件或手動編寫代碼以在定時器任務內ping服務器並在其中執行代碼。 –