我有一个应用程序,它与Yahoo weather API联系以获得当地的风速。获得风速并不是至关重要但是可取的并且确实提高了我的应用程序的准确性。我有一个方法,在调用refreshWeather之前首先检查活动的Internet连接。这一切都很常见。但是,我想添加代码来取消请求,如果它没有数据...说... 15秒。这是方法。任何建议表示赞赏。
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 :(得分:0)
我自己想通了。我正在添加解决方案以防其他人正在搜索相同的内容。
URLConnection connection = url.openConnection();
connection.setConnectTimeout(15000); //15 seconds
connection.setReadTimeout(15000); //15 seconds