2016-04-16 18 views
1

我在我的應用程序中使用了Retrofit2進行網絡通話,並且我希望在網絡通話期間在我的應用程序中獲取任何類型的錯誤時向用戶顯示警報。我可以在Retrofit的重寫方法中的網絡呼叫期間向用戶顯示警報,但是我不想爲每個聯網呼叫編寫方法,當有任何錯誤發生時顯示時,是否有任何方法只寫一次該警報方法。在Retrofit2中遇到任何類型的錯誤,顯示警告給用戶?

任何形式的幫助對我都有幫助。

+0

我已經添加了一個可能的解決方案@R ajeev,請檢查它 – Lampard

回答

0

您需要添加一個攔截器像下面

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.

希望它有幫助。

+0

它不工作,我執行相同的。 – Rajeev

+0

以及我在發佈之前測試了代碼。你能告訴我你有什麼錯誤嗎? – Morya

0

在其onFailure處方法,你可以通過如下這樣做表明舉杯用戶:

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

      } 
     }); 
1

做一個實用工具類,並創建警報對話框的網絡錯誤這樣的方法:

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(); 
    } 

然後在你的web服務調用失敗方法中調用上面的方法:

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

      } 
     }); 
相關問題