2016-12-04 7 views
0

Yahoo Weather APIに連絡して地元の風速を取得するアプリがあります。風速を得ることは重要ではありませんが、望ましいことであり、アプリの精度を向上させます。私はrefreshWeatherを呼び出す前にアクティブなインターネット接続を最初にチェックするメソッドを持っています。それはすべてうまくいく。ただし、15秒後にデータが取得されない場合は、リクエストをキャンセルするコードを追加します。方法は次のとおりです。任意の提案が高く評価されました。一定時間後にURL接続をキャンセルする

public void refreshWeather (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(); 
       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("No wind information found for your location")); 
        return; 
       } 

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

} 

答えて

0

私はそれを自分で考え出しました。他の誰かが同じものを探している場合に備えて、私はその解決策を追加しています。

URLConnection connection = url.openConnection(); 
    connection.setConnectTimeout(15000); //15 seconds 
    connection.setReadTimeout(15000); //15 seconds 
関連する問題