【问题标题】:Async task downloader will fail when the connection lost连接丢失时,异步任务下载器将失败
【发布时间】:2013-12-15 17:59:40
【问题描述】:
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次,然后敬酒。谢谢

【问题讨论】:

    标签: android networking asynchronous android-asynctask download


    【解决方案1】:

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

     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

    【讨论】:

    • 谢谢,我已经使用 try catch 发出了 toast 警告,但是,如果用户再次连接,我该如何处理?谢谢
    • 您可以设置广播接收器来接收重新建立连接的事件,或者手动编写代码以在计时器任务中 ping 服务器并在其中执行您的代码。
    【解决方案2】:

    如果您的文件没有下载,您将自己的逻辑点击2次下载文件,因为当网络断开时,下载将停止。

    【讨论】:

      猜你喜欢
      • 2015-08-07
      • 1970-01-01
      • 1970-01-01
      • 2019-02-01
      • 2019-07-25
      • 2021-07-19
      • 2014-08-15
      • 2012-10-31
      相关资源
      最近更新 更多