LoginSignup
17

More than 1 year has passed since last update.

OkHttp で遅い通信環境を再現させる

Last updated at Posted at 2016-02-27

Android の通信ライブラリでおなじみの OkHttp で、通信に時間がかかる状況を再現させることができます。
RetrofitGlide で OkHttp を使っている場合でももちろん OK です。

背景

  • 通信に時間がかかる場合の、アプリの UI/UX を確認したい。
  • フリーズしたように見えないか
  • 適度に進捗表示をしているか
  • 画面遷移後の通信のコールバック処理が適切かどうかを確認したい。
  • うまく対処していない場合、下のようなエラーになります
  • getActivity() が null を返す
  • View 操作で NullPointerException
  • Fragment 操作で java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

実現方法

OkHttp の Interceptor を使って、指定時間通信を遅らせる Interceptor を作る。
この Interceptor を OkHttp の networkInterceptors に追加する。
Stetho の Network Inspection もこの方法ですね。)

実装

DelayInterceptor

DelayInterceptor.java
class DelayInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        try {
            Thread.sleep(5000); // 5秒遅らせる。
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return chain.proceed(request);
    }

}

Client に DelayInterceptor を追加する

OkHttpClient client = new OkHttpClient();
client.networkInterceptors().add(new DelayInterceptor());

簡単ですね。

最後に

  • 上のコードでは Thread.sleep(...) の値を固定にしていますが、SharedPreference でカスタマイズできるようにしておくと良いでしょう。
  • 画面遷移後のコールバック対応は、RxJava を使っているなら、RxLifecycle を使う手もあります。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17