Reputation: 147
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?
Upvotes: 5
Views: 9442
Reputation: 401
You can check for Internet and listen for it's state using Rx-receivers
see : https://github.com/f2prateek/rx-receivers
Upvotes: 1
Reputation: 48
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();
}
}
Upvotes: 0
Reputation: 896
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.
Upvotes: 3
Reputation: 4036
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.
Upvotes: 7
Reputation: 48
//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);
}
Upvotes: -3