一段时间后HttpUrlConnection超时

时间:2015-01-04 22:45:06

标签: android android-asynctask

我有一个AsyncTask来下载图像,这些图像可能会工作几分钟并在一段时间后停止工作。

我需要知道是否有更好的方法来解决此问题

private void setupChart(String url){
    showAsyncIndicator();

    new DownloadImageTask(chartView).execute(url);

}

private class DownloadImageTask extends AsyncTask<String,Void, Bitmap>{

    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage){
        this.bmImage = bmImage;

    }

    @Override
    protected Bitmap doInBackground(String... urls) {
        String urlDisplay = urls[0];

        Bitmap mIcon = null;

        InputStream in;

        int responseCode ;

        try {
            URL  url = new URL(urlDisplay);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();

            responseCode = connection.getResponseCode();

            if(responseCode == HttpURLConnection.HTTP_OK){
                in = connection.getInputStream();

                mIcon = BitmapFactory.decodeStream(in);
                in.close();



            }


        } catch (Exception e) {
            Log.d("Exception",e.toString());
        }

        return mIcon;
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);

        clearAsyncIndicator();
    }
}

private void showAsyncIndicator(){
    // doing someThings here later
}


private void clearAsyncIndicator(){
     // doing someThings here later
}

1 个答案:

答案 0 :(得分:0)

如果问题是http超时错误,您可以尝试connection.setConnectTimeout(time);改变超时但无论如何我认为你应该使用Volley来获取图像,对我来说这是更好的解决方案......

http://developer.android.com/training/volley/index.html

你可以找到很多关于它的教程