关于android:如何观察RxAndroid中的网络变化

How to observe network changes in RxAndroid

我正在使用此处提供的代码。

我将这些代码块作为类放入我的项目的util包中。然后在主活动课中,我写了这个。.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class MenuActivity {

// Variable declaration
  private final CompositeSubscription mConnectionSubscription = new CompositeSubscription();

@Override
protected void onCreate(Bundle savedInstanceState) {

    // Some initialisation of UI elements done here

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

}

我的目标是监视更改,并在网络更改为true false时静态更改MyApp类中定义的变量MyApp.isConnected。帮助将不胜感激。谢谢??


您要求我在另一个主题中给出答案。我迟到了,因为我需要一些时间来开发和测试解决方案,而我认为这已经足够了。

我最近创建了一个名为ReactiveNetwork的新项目。

它是开源的,可在以下网址获得:https://github.com/pwittchen/ReactiveNetwork。

您可以将以下依赖项添加到您的build.gradle文件中:

1
2
3
dependencies {
  compile 'com.github.pwittchen:reactivenetwork:x.y.z'
}

然后,您可以将x.y.z替换为最新的版本号。

之后,您可以通过以下方式使用库:

1
2
3
4
5
6
7
8
9
10
11
12
 ReactiveNetwork.observeNetworkConnectivity(context)        
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Action1<ConnectivityStatus>() {
      @Override public void call(Connectivity connectivity) {
        if(connectivity.getState() == NetworkInfo.State.DISCONNECTED) {
          Timber.i("Connection lost");
        } else if(connectivity.getState() == NetworkInfo.State.CONNECTED) {
          Timber.i("Connected");
        }
      }
    });

如果只想对单一类型的事件做出反应,也可以使用RxJava中的filter(...)方法。

您可以在onResume()方法中创建订阅,然后在Activity中的onPause()方法中取消订阅。

您可以在GitHub上该项目的网站上找到更多用法示例和示例应用程序。

此外,您可以从Android API中了解有关NetworkInfo.State枚举的信息,该库现在使用该枚举。


尝试使用rxnetwork-android:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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();
    }
}