java - 检查互联网连接 OKHTTP

标签 java android android-studio https okhttp

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

最佳答案

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

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

关于java - 检查互联网连接 OKHTTP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40389163/

相关文章:

java - 过滤scala中对象列表的列表属性

android - 对话框主题动画问题

android - Firebase:是否可以为 FCM 做自定义通知

android - 在 Android Studio 中运行重建项目后会发生什么?

java - 在java中,是使用audioManager时的流类型。 (如STREAM_MUSIC)流类型是什么意思?

java - 使用 Calender 或 java 中的任何类查找上个月名称

java - int 表示计时器错误 : Local variable ans defined in an enclosing scope must be final or effectively final

java - 如何使用 ejb3 和注释在数据源中注入(inject)依赖项

android - 在 Android Studio 中找不到默认 Activity

java - 录音机状态无效(文件路径错误?)