2016-11-02 5 views
3

Я использую следующий код, чтобы сделать api-вызов и прямой пользователь на страницу на основе полученного ответа. Как проверить подключение к Интернету?Проверьте подключение к Интернету OKHTTP

Я использую OK клиент HTTP и мой код выглядит следующим образом:

button.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      String url = "https://xxxxxxxx/" + orderLineId; 
      JSONObject jSon = new JSONObject(); 
      try { 
       jSon.put("prescription_xxxxx", prescriptionIntervalId); 
       jSon.put("prescription_xxxxxxx", false); 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
      String data = jSon.toString(); 
      RequestBody body = RequestBody.create(JSON, data); 
      Request request = new Request.Builder() 
        .url(url) 
        .addHeader("Content-Type", "application/json") 
        .addHeader("Authorization", token) 
        .addHeader("Accept", "application/json") 
        .put(body) 
        .build(); 

      client.newCall(request).enqueue(new Callback() {@Override 
       public void onFailure(Request request, IOException e) { 

        AlertDialog.Builder dialog = new AlertDialog.Builder(AutoRefillActivity.this); 
        dialog.setMessage("Something went wrong. Check connection.") 
          .setCancelable(false) 
          .setPositiveButton("OK", new DialogInterface.OnClickListener() { 
           public void onClick(DialogInterface dialog, int id) { 
            onBackPressed(); 
           } 
          }); 
        AlertDialog alert = dialog.create(); 
        alert.show(); 
       } 

       @Override 
       public void onResponse(Response response) throws IOException { 

        if(response.code()==401){ 

         AlertDialog.Builder dialog = new AlertDialog.Builder(AutoRefillActivity.this); 
         dialog.setMessage("Device was idle for too long please login again.") 
           .setCancelable(false) 
           .setPositiveButton("OK", new DialogInterface.OnClickListener() { 
            public void onClick(DialogInterface dialog, int id) { 
             onBackPressed(); 
            } 
           }); 
         AlertDialog alert = dialog.create(); 
         alert.show(); 

        } 
        else { 

         Intent paymentSummary = new Intent(AutoRefillActivity.this,PPPaymentSummaryActivityNew.class); 
         paymentSummary.putExtra(PPPaymentSummaryActivityNew.EXTRA_ORDER,String.valueOf(orderLineId)); 
         paymentSummary.putExtra("order_line_id",orderLineId); 
         paymentSummary.putExtra(PPPaymentSummaryActivityNew.EXTRA_CATEGORY_CODE,categoryCode); 
         paymentSummary.putExtra("prescriptionIntervalId",prescriptionIntervalId); 
         paymentSummary.putExtra("available",available); 
         paymentSummary.putExtra("token",token); 
         Bundle newBundle = new Bundle(); 
         newBundle.putParcelable(PPPaymentSummaryActivityNew.EXTRA_PRODUCT,product); 
         paymentSummary.putExtras(newBundle); 
         startActivity(paymentSummary); 

        } 
       } 

Хотя я поставил окно предупреждения в OnFailure запроса асинхронной. Это не работает. Я все еще могу отключить интернет, и мое приложение падает. Любое решение?

+0

Привет, вы решить проблема HttpStatusCode? Я застрял с той же проблемой ... спасибо. –

ответ

4

следующий метод будет определить, доступен ли интернет

/** 
* 
* @param context 
* @return true if connected to Internet 
* 
*/ 
public static boolean isNetworkAvailable(final Context context) { 
    final ConnectivityManager cm = (ConnectivityManager) 
      context.getSystemService(Context.CONNECTIVITY_SERVICE); 
    if (cm == null) return false; 
    final NetworkInfo networkInfo = cm.getActiveNetworkInfo(); 
    // if no network is available networkInfo will be null 
    // otherwise check if we are connected 
    return (networkInfo != null && networkInfo.isConnected()); 
} 

Затем сделать ваши вещи веб-службы, как этот

if(isNetworkAvailable(context)){ 
    //do something 
} 
1

Этот вопрос был дан ответ миллион раз. Используйте поиск - результат будет как

private boolean isNetworkConnected() { 
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 

    return cm.getActiveNetworkInfo() != null; 
} 

 Смежные вопросы

  • Нет связанных вопросов^_^