【问题标题】:Check internet connection OKHTTP检查互联网连接 OKHTTP
【发布时间】:2017-03-16 07:25:39
【问题描述】:

我正在使用以下代码进行 api 调用并根据收到的响应将用户引导到页面。如何检查互联网连接?

我正在使用 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 中放置了一个警告框。这是行不通的。我仍然可以关闭互联网并且我的应用程序崩溃了。有什么解决办法吗?

【问题讨论】:

  • 您好,您解决了 HttpStatusCode 问题吗?我遇到了同样的问题...谢谢。

标签: java android android-studio https okhttp


【解决方案1】:

下面的方法会判断网络是否可用

/**
 *
 * @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
}

【讨论】:

  • 这只会在您连接到网络时通知您。如果您已连接到 Internet,则不会。
【解决方案2】:

这个问题以前被回答过一百万次。使用搜索 - 结果会是这样的

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

    return cm.getActiveNetworkInfo() != null;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-15
    • 2014-02-08
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 2015-08-20
    • 2012-11-13
    • 2011-04-08
    相关资源
    最近更新 更多