用AsyncTask关闭InputStream

时间:2016-12-09 00:51:20

标签: android android-asynctask inputstream

我有以下代码。它运作良好,但我意识到我从未关闭InputStream。研究,似乎我应该通过在我的一次捕获后添加一个最终来关闭它。

Q1:我需要关闭InputStream吗?

Q2:如果是的话,怎么样?

以下是我的代码示例:

    public void refreshWind (final double lat, final double lon){

    new AsyncTask<String, Void, String>() {
        @Override
        protected String doInBackground(String... strings) {

            String YQL = String.format("select * from weather.forecast where woeid in (SELECT woeid FROM geo.places WHERE text=\"(%s,%s)\")", lat, lon);
            String endpoint = String.format("https://query.yahooapis.com/v1/public/yql?q=%s&format=json", Uri.encode(YQL));

            try {
                URL url = new URL(endpoint);
                URLConnection connection =url.openConnection();
                connection.setReadTimeout(10 *1000);         
                connection.setConnectTimeout(10 *1000);      
                InputStream inputStream =connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder result = new StringBuilder();
                String line;
                while ((line = reader.readLine()) !=null){
                    result.append(line);
                }
                return result.toString();
            }catch (Exception e) {
                error = e;
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {

            if (s ==null && error !=null){
                callback.serviceFailure(error);
                return;
            }
            try {
                JSONObject data = new JSONObject(s);
                JSONObject queryResults =data.optJSONObject("query");
                int count =queryResults.optInt("count");
                if (count ==0){
                    callback.serviceFailure(new LocationWeatherException("Wind information not available at this time."));
                    return;
                }

                Channel channel = new Channel();
                channel.populate(queryResults.optJSONObject("results").optJSONObject("channel"));
                callback.serviceSuccess(channel);
            }catch (JSONException e) {
                callback.serviceFailure(e);
            }
        }
    }.execute();

}

1 个答案:

答案 0 :(得分:2)

我认为您应该在close()上致电BufferedReaderInputStream包裹您的finally。如果发生异常,您应该在protected String doInBackground(String... strings) { String YQL = String.format("select * from weather.forecast where woeid in (SELECT woeid FROM geo.places WHERE text=\"(%s,%s)\")", lat, lon); String endpoint = String.format("https://query.yahooapis.com/v1/public/yql?q=%s&format=json", Uri.encode(YQL)); BufferedReader reader = null; try { URL url = new URL(endpoint); URLConnection connection =url.openConnection(); connection.setReadTimeout(10 *1000); connection.setConnectTimeout(10 *1000); InputStream inputStream =connection.getInputStream(); reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder result = new StringBuilder(); String line; while ((line = reader.readLine()) !=null){ result.append(line); } return result.toString(); } catch (Exception e) { error = e; } finally { // should have no effect if stream already closed if (reader != null) { reader.close(); } } return null; } 关闭中调用它:

line-height

来自Javadoc for BufferedReader#close()

  

关闭流并释放与其关联的所有系统资源。关闭流后,进一步的read(),ready(),mark(),reset()或skip()调用将抛出IOException。 关闭之前关闭的流无效。