在 Retrofit2 中出现任何类型的错误时向用户显示警报?

Show alert to user when get any kind of error in Retrofit2?

我在我的应用程序中使用 Retrofit2 进行网络调用,我想在网络调用期间我的应用程序出现任何类型的错误时向用户显示警报。我可以在 Retrofit 的覆盖方法中的网络调用期间向用户显示警报,但我不想为每个网络调用编写方法,有没有办法在任何错误出现时只写一次该警报方法。

任何形式的帮助都会对我有所帮助。

您需要像下面这样添加一个拦截器

 public static class LoggingInterceptor implements Interceptor
    {
      Context context;

      public LoggingInterceptor(Context context)
         {
            this.context = context;
         }

      @Override
      public Response intercept(Chain chain) throws IOException
         {
            Request request = chain.request();
            Response response = chain.proceed(request);
            response.code();
            if(response.code() != 200)
            {
              backgroundThreadShortToast(context, "response code is not 200");
            }
            else
            {
              backgroundThreadShortToast(context, "response code is 200");
            }
            return response.newBuilder().body(ResponseBody.create(response.body().contentType(), "")).build();
            //return response;
         }
    }

 public static void backgroundThreadShortToast(final Context context, final String msg)
    {
      if(context != null && msg != null)
      {
         new Handler(Looper.getMainLooper()).post(new Runnable()
            {

              @Override
              public void run()
                 {
                    Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                 }
            });
      }
    }

然后将此拦截器添加到您的主要改造客户端

    client.interceptors().add(new LoggingInterceptor(context));

在上述情况下,为响应代码 == 200 干杯。

希望对您有所帮助。

在其 onFailure 方法中,您可以通过如下方式向用户显示 Toast:

            @Override
            public void onFailure(Throwable t) {
                Toast.makeText(yourContext, t.getLocalizedMessage(), Toast.LENGTH_LONG).show();

            }
        });

制作一个实用程序 class 并创建一个网络错误警报对话框的方法,如下所示:

public static void showNetworkDialog(context){
        AlertDialog.Builder alertDialogBuilder=new AlertDialog.Builder(context);

        alertDialogBuilder.setTitle("Network Error");

        alertDialogBuilder
                .setMessage("Check Internet Connection!")
                .setCancelable(false)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();
    }

然后在你的webservice调用失败方法中直接调用上面的方法即可:

@Override
            public void onFailure(Throwable t) {
               Utils.showNetworkDialog(context);

            }
        });