[英]Handle remote exception in Asynctask
這是Asynctask
方法:
public class Read extends AsyncTask<String, Integer, String> {
ProgressDialog dialog;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
sUrl = sUrl.trim();
json = lastTweet(sUrl);
return json.getString(params[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
}
}
和相關的lastTweet方法:
public JSONObject lastTweet(String username)
throws ClientProtocolException, IOException, JSONException {
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
}
}
所有這些代碼都可以正常工作。 到目前為止,沒有問題。 但是,我想做些小事情。 當HTTP傳輸期間失去連接時,將 引發 RemoteException
且應用程序崩潰 。
我試圖在Async
方法中處理異常,但無法做到這一點。
有什么辦法可以處理這樣的異常?
您可以在執行Read
AsyncTask
之前檢查網絡連接
1.檢查連接
if(ifConnectionIsAvailable)
new Read().execute();
2. 設置連接超時
HttpGet get = new HttpGet(url.toString());
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;// in milliseconds
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse r = httpClient.execute(get);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.