我有这段代码来检查互联网连接是否可用。
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;
}
现在我想使用RxJava / RxAndroid执行相同的任务。那我怎么能这样做呢?
答案 0 :(得分:5)
如果您被允许使用ConnectivityManager
,这是检查互联网连接的快捷方式:
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());
}
然后按如下方式使用它:
private Observable<Object> executeNetworkCall() {
return isInternetOn(context)
.filter(connectionStatus -> connectionStatus)
.switchMap(connectionStatus -> doNetworkCall()));
}
如果您需要更多信息,此answer会提供更详细的说明。
答案 1 :(得分:2)
您可以使用ReactiveNetwork。这个库可以用于检查引擎盖下的连接状态,您可以通过订阅它来观察连接状态。
答案 2 :(得分:0)
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();
}
}
答案 3 :(得分:0)
您可以使用 Rx接收器
检查互联网并收听状态答案 4 :(得分:-2)
//使用以下代码ping任何网站以检查互联网连接
public boolean isConnected() throws InterruptedException, IOException
{
String command = "ping -c 1 google.com";
return (Runtime.getRuntime().exec (command).waitFor() == 0);
}