在Async类Android中设置超时

时间:2014-06-14 07:27:53

标签: android asynchronous

我正在使用下面的Async类,但我没有任何想法如何在异步类中设置超时

有些时候互联网连接速度很慢,然后Async类需要很长时间

private class GetServerChallans extends AsyncTask<String, Void, String> {
         @Override
            protected String doInBackground(String... urls) {
              String response = "";
              HttpEntity resEntity;
                try {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost("wwww...........");

                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                    nameValuePairs.add(new BasicNameValuePair("token",strtoken));
                    nameValuePairs.add(new BasicNameValuePair("customer_code",strcustomer_code));
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    // Execute HTTP Post Request
                    HttpResponse responsePOST = httpclient.execute(httppost);
                     resEntity = responsePOST.getEntity();
                     response=EntityUtils.toString(resEntity);
                } catch (Exception e) {
                  e.printStackTrace();
                }

              return response;
            }

            @SuppressLint("DefaultLocale")
            @Override
            protected void onPostExecute(String result) {
                pd.dismiss();
                if(result!=null)
                {

                }

                }
            }

            @Override
            protected  void onPreExecute()
            {
                //pd = ProgressDialog.show(MyProfile.this, "","Please wait...");

            }
          }

请帮助我如何在Async类中使用超时

提前致谢

1 个答案:

答案 0 :(得分:0)

HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);