我想在连接尝试上设置超时,例如10秒。但我对使用网络技术的线程或任何东西并不是很好。我不知道接下来应该做什么。
这是我的班级:
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(RecipeActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting to server");
dialog.show();
dialog.setCancelable(false);
}
@Override
protected Boolean doInBackground(String... urls) {
try {
HttpGet httpPost = new HttpGet(urls[0]);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(httpPost);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray array = new JSONArray(data);
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
Recipe rec = new Recipe();
rec.setName(object.getString("name"));
rec.setImage(object.getString("image"));
rec.setCalories(object.getInt("calories"));
rec.setIngredients(object.getString("ingredients"));
rec.setInstructions(object.getString("instructions"));
rec.setTime(object.getString("time"));
rec.setDescription(object.getString("description"));
rec.setNumberIngred(object.getString("numberingred"));
recipes.add(rec);
}
return true;
}
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if (result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}