android - 连接丢失时,异步任务下载器将失败

标签 android networking asynchronous android-asynctask download

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次,然后 toast 。谢谢

最佳答案

首先要做的是在发出请求之前检查连接。

 ConnectivityManager connMgr = (ConnectivityManager) 
        getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {
        // fetch data
    } else {
        // display error
    }

第二个:

private String downloadUrl(String myurl) throws IOException {
    InputStream is = null;
    // Only display the first 500 characters of the retrieved
    // web page content.
    int len = 500;

    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        Log.d(DEBUG_TAG, "The response is: " + response);
        is = conn.getInputStream();

        // Convert the InputStream into a string
        String contentAsString = readIt(is, len);
        return contentAsString;

    // Makes sure that the InputStream is closed after the app is
    // finished using it.
    } finally {
        if (is != null) {
            is.close();
        } 
    }
}

如上所示,使您的代码部分抛出 IOException

关于android - 连接丢失时,异步任务下载器将失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20597821/

相关文章:

android - onSharedPreferenceChanged 问题中的 setSummary(txt)

java - 我无法将我的 Android 应用程序连接到 MongoDB

git - 无法在学校网络上推送到github

networking - 通过互联网设置 TFS

javascript - 在 Bluebird 中处理多个嵌套异步操作(promises)

c# - MVC 中的异步/等待 - 为什么在长时间运行的操作期间释放线程很重要

java - 异步执行长时间运行的 liquibase 数据库更新

android - 更改 StreetView<->Satellite Google Maps Android

安卓 : drop down a list of items without a spinner

java - 我可以终止等待 TCP 连接进入的线程吗?