处理Asynctask中的远程异常

时间:2013-07-14 19:29:13

标签: android android-asynctask remoteexception

以下是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方法中处理异常,但无法执行此操作。

有办法处理这种异常吗?

1 个答案:

答案 0 :(得分:1)

您可以在执行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);