如何在android中主动检查互联网连接或检查连接超时?

时间:2015-08-22 13:18:41

标签: java android android-asynctask connection-timeout internet-connection

在我的应用程序中,如果没有互联网连接,我在asynctask方法中的onPostExecute()上得到以下结果

  

"值无法将java.lang.String类型转换为JSONArray"。

因此我需要检查是否有持续的互联网连接。此外,如果存在连接超时,我需要向用户显示消息。

那么,我该如何解决这个问题呢?

P.S现在我正在检查以下代码是否没有连接互联网

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class InternerConnection {
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}

但是如果网络不好,我会收到上述引用的消息。

已编辑

这是我的onPostExecute和doInBackground方法

@Override
protected void onPostExecute(String result) {

try {
// dialog.dismiss();
Log.v("esty", "Restaurent output :" + result);

Restaurants rd = new Restaurants();
JSONObject json = new JSONObject(result);

JSONObject obj = json.getJSONObject("Restaurant");
String ID = obj.getString("Id");

String RestaurantBrandId = obj.getString("RestaurantBrandId");

String RestaurantBrand = obj.getString("RestaurantBrand");

/*.......................... Rest of the JSON parsing
..................................................*/
((RestaurantsDetailsGeneralActivity) activity).Bind(rd);

super.onPostExecute(result);
} catch (Exception ex) {

Log.v("error", "Restaurant detail :" + ex.getMessage());

}
}


@Override
protected String doInBackground(Void... params) {

try {



HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpParams p = new BasicHttpParams();
HttpClient httpclient = new DefaultHttpClient(p);

String url = "http://89b69f2297434a0eac543944c620faae.cloudapp.net/RestaurantsApi/Details";



List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("restaurantNumber",
AppGlobal.ResturantNumber));


HttpClient httpClient = new DefaultHttpClient();
String paramsString = URLEncodedUtils.format(nameValuePairs,
"UTF-8");
HttpGet httpget = new HttpGet(url + "?" + paramsString);

ResponseHandler<String> responseHandler = new BasicResponseHandler();

String responseBody = httpclient.execute(httpget, responseHandler);

return responseBody;
} catch(ConnectException e){             
  //not getting this exception. Do in background always returns a result.         
       return e.getMessage();
   }catch (SocketTimeoutException ste){
       Log.v("esty", ste.toString());

       return ste.toString();
   }catch (Exception ex) {

return ex.getMessage();
}

}

1 个答案:

答案 0 :(得分:0)

似乎最好的做法是找出发生连接失败时遇到特定错误的原因,并修复代码以便优雅地处理失败。它可能比试图监听超时更容易。你能在onPostExecute方法中发布一些代码吗?