简体   繁体   中英

RxJava/RxAndroid Check internet connection available or not

I have this code to check if internet connection is available or not.

    public static boolean  isOnline() {
    Runtime runtime = Runtime.getRuntime();
    try {
        Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int exitValue = ipProcess.waitFor();
        return (exitValue == 0);
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
    return false;
}

Now i want to do the same task using RxJava/RxAndroid. so how can I do that?

If you're allowed to use the ConnectivityManager this is a quick way to check for internet connection:

public static Observable<Boolean> isInternetOn(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return Observable.just(activeNetworkInfo != null && activeNetworkInfo.isConnected());
    }

and then use it as follows:

private Observable<Object> executeNetworkCall() {
    return isInternetOn(context)
            .filter(connectionStatus -> connectionStatus)
            .switchMap(connectionStatus -> doNetworkCall()));
}

If you need more info, this answer provides much more detailed instructions.

You can use ReactiveNetwork . This library do all work for checking connectivity state under hood and you can just observe connectivity state by subscribing to it.

You can check for Internet and listen for it's state using Rx-receivers

see : https://github.com/f2prateek/rx-receivers

public class MainActivity extends AppCompatActivity{
  private Subscription sendStateSubscription;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      final Observable<RxNetwork.State> sendStateStream =
              RxNetwork.stream(this);

      sendStateSubscription = AppObservable.bindActivity(
            this, sendStateStream
      ).subscribe(new Action1<RxNetwork.State>() {
          @Override public void call(RxNetwork.State state) {
              if(state == RxNetwork.State.NOT_CONNECTED)
                  Timber.i("Connection lost");
              else
                  Timber.i("Connected");
          }
      });
  }

  @Override protected void onDestroy() {
      sendStateSubscription.unsubscribe();
      sendStateSubscription = null;

      super.onDestroy();
  }
}

//ping any website with the following code to check for internet connection

public boolean isConnected() throws InterruptedException, IOException
{
    String command = "ping -c 1 google.com";
    return (Runtime.getRuntime().exec (command).waitFor() == 0);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM