Android library listening network connection state and Internet connectivity with RxJava Observables

Overview

ReactiveNetwork

Android Arsenal

view website with documentation: RxJava1.x, RxJava2.x

ReactiveNetwork is an Android library listening network connection state and Internet connectivity with RxJava Observables. It's a successor of Network Events library rewritten with Reactive Programming approach. Library supports both new and legacy network monitoring strategies. Min sdk version = 9.

Current Branch Branch Artifact Id Build Status Coverage Maven Central
RxJava1.x reactivenetwork Build Status for RxJava1.x codecov Maven Central
☑️ RxJava2.x reactivenetwork-rx2 Build Status for RxJava2.x codecov Maven Central

Contents

Usage

Please note: Due to memory leak in WifiManager reported in issue 43945 in Android issue tracker it's recommended to use Application Context instead of Activity Context.

Observing network connectivity

We can observe Connectivity with observeNetworkConnectivity(context) method in the following way:

ReactiveNetwork
  .observeNetworkConnectivity(context)
  .subscribeOn(Schedulers.io())
  ... // anything else what you can do with RxJava
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(connectivity -> {
      // do something with connectivity
      // you can call connectivity.state();
      // connectivity.type(); or connectivity.toString();
  });

When Connectivity changes, subscriber will be notified. Connectivity can change its state or type.

Errors can be handled in the same manner as in all RxJava observables. For example:

ReactiveNetwork
  .observeNetworkConnectivity(context)
  .subscribeOn(Schedulers.io())
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(
       connectivity -> /* handle connectivity here */,
       throwable    -> /* handle error here */
   );

We can react on a concrete state, states, type or types changes with the filter(...) method from RxJava, hasState(NetworkInfo.State... states) and hasType(int... types) methods located in ConnectivityPredicate class.

ReactiveNetwork
  .observeNetworkConnectivity(context)
  .subscribeOn(Schedulers.io())
  .filter(ConnectivityPredicate.hasState(NetworkInfo.State.CONNECTED))
  .filter(ConnectivityPredicate.hasType(ConnectivityManager.TYPE_WIFI))
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(connectivity -> {
      // do something
  });

observeNetworkConnectivity(context) checks only connectivity with the network (not Internet) as it's based on BroadcastReceiver for API 20 and lower and uses NetworkCallback for API 21 and higher. Concrete WiFi or mobile network may be connected to the Internet (and usually is), but it doesn't have to.

You can also use method:

Observable<Connectivity> observeNetworkConnectivity(Context context, NetworkObservingStrategy strategy)

This method allows you to apply your own network observing strategy and is used by the library under the hood to determine appropriate strategy depending on the version of Android system.

Connectivity class

Connectivity class is used by observeNetworkConnectivity(context) and observeNetworkConnectivity(context, networkObservingStrategy) methods. It has the following API:

Connectivity create()
Connectivity create(Context context)

NetworkInfo.State state()
NetworkInfo.DetailedState detailedState()
int type()
int subType()
boolean available()
boolean failover()
boolean roaming()
String typeName()
String subTypeName()
String reason()
String extraInfo()

// and respective setters

class Builder

Network Observing Strategies

Right now, we have the following strategies for different Android versions:

  • LollipopNetworkObservingStrategy
  • MarshmallowNetworkObservingStrategy
  • PreLollipopNetworkObservingStrategy

All of them implements NetworkObservingStrategy interface. Concrete strategy is chosen automatically depending on the Android version installed on the device. With observeNetworkConnectivity(context, strategy) method we can use one of these strategies explicitly.

Observing Internet connectivity

Observing Internet connectivity continuously

We can observe connectivity with the Internet continuously in the following way:

ReactiveNetwork
  .observeInternetConnectivity()
  .subscribeOn(Schedulers.io())
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(isConnectedToInternet -> {
      // do something with isConnectedToInternet value
  });

An Observable will return true to the subscription (disposable) if device is connected to the Internet and false if not.

Internet connectivity will be checked as soon as possible.

Please note: This method is less efficient than observeNetworkConnectivity(context) method, because in default observing strategy, it opens socket connection with remote host (default is www.google.com) every two seconds with two seconds of timeout and consumes data transfer. Use this method if you really need it. Optionally, you can dispose subscription (disposable) right after you get notification that Internet is available and do the work you want in order to decrease network calls.

Methods in this section should be used if they are really needed due to specific use cases.

If you want to customize observing of the Internet connectivity, you can use InternetObservingSettings class and its builder. They allow to customize monitoring interval in milliseconds, host, port, timeout, initial monitoring interval, timeout, expected HTTP response code, error handler or whole observing strategy.

InternetObservingSettings settings = InternetObservingSettings.builder()
  .initialInterval(initialInterval)
  .interval(interval)
  .host(host)
  .port(port)
  .timeout(timeout)
  .httpResponse(httpResponse)
  .errorHandler(testErrorHandler)
  .strategy(strategy)
  .build();

ReactiveNetwork
  .observeInternetConnectivity(settings)
  .subscribeOn(Schedulers.io())
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(isConnectedToInternet -> {
      // do something with isConnectedToInternet value
  });

These methods are created to allow the users to fully customize the library and give them more control.

Please note, not all parameters are relevant for all strategies.

For more details check JavaDoc at: http://pwittchen.github.io/ReactiveNetwork/javadoc/RxJava2.x

Checking Internet Connectivity once

If we don't want to observe Internet connectivity in the interval with Observable<Boolean> observeInternetConnectivity(...) method, we can use Single<Boolean> checkInternetConnectivity(), which does the same thing, but only once. It may be helpful in the specific use cases.

Single<Boolean> single = ReactiveNetwork.checkInternetConnectivity();

single
  .subscribeOn(Schedulers.io())
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(isConnectedToInternet -> {
      // do something with isConnectedToTheInternet
  });

As in the previous case, you can customize this feature with the InternetObservingSettings class and its builder.

InternetObservingSettings settings = InternetObservingSettings.builder()
  .initialInterval(initialInterval)
  .interval(interval)
  .host(host)
  .port(port)
  .timeout(timeout)
  .httpResponse(httpResponse)
  .errorHandler(testErrorHandler)
  .strategy(strategy)
  .build();

Single<Boolean> single = ReactiveNetwork.checkInternetConnectivity(settings);

single
  .subscribeOn(Schedulers.io())
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(isConnectedToInternet -> {
      // do something with isConnectedToTheInternet
  });

Basic idea is the same. With just have Single<Boolean> return type instead of Observable<Boolean> and we don't have int initialIntervalInMs and int intervalInMs parameters.

As previously, these methods are created to allow the users to fully customize the library and give them more control.

For more details check JavaDoc at: http://pwittchen.github.io/ReactiveNetwork/javadoc/RxJava2.x

Internet Observing Strategies

Right now, we have the following strategies for observing Internet connectivity:

  • SocketInternetObservingStrategy - monitors Internet connectivity via opening socket connection with the remote host
  • WalledGardenInternetObservingStrategy - opens connection with a remote host and respects countries in the Walled Garden (e.g. China)

All of these strategies implements NetworkObservingStrategy interface. Default strategy used right now is WalledGardenInternetObservingStrategy, but with checkInternetConnectivity(strategy) and observeInternetConnectivity(strategy) method we can use one of these strategies explicitly.

Custom host

If you want to ping custom host during checking Internet connectivity, it's recommended to use SocketInternetObservingStrategy. You can do it as follows:

InternetObservingSettings settings = InternetObservingSettings.builder()
  .host("www.yourhost.com")
  .strategy(new SocketInternetObservingStrategy())
  .build();

ReactiveNetwork
  .observeInternetConnectivity(settings)
  .subscribeOn(Schedulers.io())
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(isConnectedToHost -> {
      // do something with isConnectedToHost
  });

If you want to use WalledGardenInternetObservingStrategy, please update HTTP response code via InternetObservingSettings. E.g set it to 200 because default is 204.

The same operation can be done with checkInternetConnectivity(strategy, host) method, which returns Single instead of Observable.

Chaining network and Internet connectivity streams

Let's say we want to react on each network connectivity change and if we get connected to the network, then we want to check if that network is connected to the Internet. We can do it in the following way:

ReactiveNetwork
  .observeNetworkConnectivity(getApplicationContext())
  .flatMapSingle(connectivity -> ReactiveNetwork.checkInternetConnectivity())
  .subscribeOn(Schedulers.io())
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(isConnected -> {
    // isConnected can be true or false
});

In case we're getting too many events related to the network changes or we want to discard previous observables (there's only one in the code snippet above) after subscribing them, we can use switchMapSingle operator instead of flatMapSingle in order to get the updates from the latest observable only. In this case, it will be observable created by checkInternetConnectivity method.

ClearText Traffic

Someties, while trying to connect to the remote server we may encounter the following message:

ClearText HTTP traffic not permitted

Due to this fact, observing Internet feature won't work properly.

It's related to Network Security Configuration. Starting with Android 9.0 (API level 28), cleartext support is disabled by default.

You have a few options to solve this issue.

Option #1

Create res/xml/network_security_config.xml file:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">Your URL(ex: 127.0.0.1)</domain>
    </domain-config>
</network-security-config>

Link it in your AndroidManifest.xml file:

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:networkSecurityConfig="@xml/network_security_config"
        ...>
        ...
    </application>
</manifest>

Option #2

Set usesCleartextTraffic parameter in <application> tag in AndroidManifest.xml file to true.

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:usesCleartextTraffic="true"
        ...>
        ...
    </application>
</manifest>

For more details, check Android documentation linked above or this StackOverflow thread: https://stackoverflow.com/a/50834600/1150795.

Integration with other libraries

We can integrate ReactiveNetwork with other libraries. Especially those, which support RxJava2. In this section, we can find examples showing how to integrate this library with the OkHttp and Retrofit.

Integration with OkHttp

In order to integrate library with OkHttp, we need to wrap HTTP request with reactive type (e.g. Observable)

private Observable<Response> getResponse(String url) {
  OkHttpClient client = new OkHttpClient();
  Request request = new Request.Builder().url(url).build();

  return Observable.create(emitter -> {
    try {
        Response response = client.newCall(request).execute();
        emitter.onNext(response);
    } catch (IOException exception) {
        emitter.onError(exception);
    } finally {
        emitter.onComplete();
    }
  });
}

Next, we can chain two streams:

ReactiveNetwork
   .observeNetworkConnectivity(getApplicationContext())
   .flatMap(connectivity -> {
     if (connectivity.state() == NetworkInfo.State.CONNECTED) {
       return getResponse("http://github.com");
     }
     return Observable.error(() -> new RuntimeException("not connected"));
   })
   .subscribeOn(Schedulers.io())
   .observeOn(AndroidSchedulers.mainThread())
   .subscribe(
       response  -> /* handle response here */,
       throwable -> /* handle error here */)
   );

In the example above, whenever we get connected to the network, then request will be performed.

For more details regarding OkHttp, please visit its official website: http://square.github.io/okhttp/.

Integration with Retrofit

We can integrate ReactiveNetwork with the Retrofit.

First, we need to configure Retrofit:

Retrofit retrofit = new Retrofit.Builder()
   .baseUrl("https://api.github.com/")
   .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
   .addConverterFactory(GsonConverterFactory.create())
   .build();

As you see, we need RxJava2CallAdapterFactory here.

Next, we need to define appropriate interface with RxJava Single types:

public interface GitHubService {
 @GET("users/{user}/repos")
 Single<List<Repo>> listRepos(@Path("user") String user);
}

and instantiate the service:

GitHubService service = retrofit.create(GitHubService.class);

Next, we want to call endpoint defined with the Retrofit whenever we get connected to the network. We can do it as follows:

ReactiveNetwork
   .observeNetworkConnectivity(getApplicationContext())
   .flatMapSingle(connectivity -> service.listRepos("pwittchen"))
   .subscribeOn(Schedulers.io())
   .observeOn(AndroidSchedulers.mainThread())
   .subscribe(
       repos     -> /* handle repos here */,
       throwable -> /* handle error here */
   );

For more details regarding Retrofit, please visit its official website: http://square.github.io/retrofit/

ProGuard configuration

-dontwarn com.github.pwittchen.reactivenetwork.library.rx2.ReactiveNetwork
-dontwarn io.reactivex.functions.Function
-dontwarn rx.internal.util.**
-dontwarn sun.misc.Unsafe

Examples

Exemplary application is located in app directory of this repository.

If you want to know, how to use this library with Kotlin, check app-kotlin directory.

Download

You can depend on the library through Maven:

<dependency>
    <groupId>com.github.pwittchen</groupId>
    <artifactId>reactivenetwork-rx2</artifactId>
    <version>x.y.z</version>
</dependency>

or through Gradle:

dependencies {
  implementation 'com.github.pwittchen:reactivenetwork-rx2:x.y.z'
}

Note #1: Please, replace x.y.z with the latest version number, which is Maven Central

Note #2: If you are using Gradle version lower than 3.0, replace implementation with compile

Tests

Tests are available in library/src/test/java/ directory and can be executed on JVM without any emulator or Android device from Android Studio or CLI with the following command:

./gradlew test

To generate test coverage report, run the following command:

./gradlew test jacocoTestReport

Code style

Code style used in the project is called SquareAndroid from Java Code Styles repository by Square available at: https://github.com/square/java-code-styles.

Static code analysis

Static code analysis runs Checkstyle, PMD, Lint, ErrorProne and NullAway. It can be executed with command:

./gradlew check

Reports from analysis are generated in library/build/reports/ directory.

Who is using this library?

These apps are using (or used) ReactiveNetwork library:

Are you using this library in your app and want to be listed here? Send me a Pull Request or an e-mail to [email protected]

Getting help

Do you need help related to using or configuring this library?

You can do the following things:

Don't worry. Someone should help you with solving your problems.

Tutorials

If you speak Spanish (Español), check out this tutorial: ReactiveNetwork - Como funciona y como se integra en una app made by Video Tutorials Android.

Caveats

Since version 0.4.0, functionality releated to observing WiFi Access Points and WiFi signal strength (level) is removed in favor of ReactiveWiFi library. If you want to use this functionality, check ReactiveWiFi project.

Changelog

See CHANGELOG.md file.

JavaDoc

JavaDoc is available at: http://pwittchen.github.io/ReactiveNetwork/javadoc/RxJava2.x

It can be generated as follows:

./gradlew androidJavadocs

In order to update JavaDoc on GitHub pages, use the following bash script:

./update_javadocs.sh

Then commit and push your changes to gh-pages branch.

Documentation

view website with documentation: RxJava1.x, RxJava2.x

It can be generated as follows:

Copy the latest README.md file from RxJava1.x or RxJava2.x branch. Then checkout to gh-pages branch and put it into appropriate directory inside docs/ directory.

You can do it as follows via bash script:

./update_docs.sh
git push

Install docsify with the following command:

npm i docsify-cli -g

Go into appropriate directory and type:

docsify init .

Right now it's already generated, so we can just update the README.md file and adjust generated files manually.

Next, we can just save changes, commit and push them to remote repository.

Releasing

See RELEASING.md file.

Contributors

References

Mentions

Supporters

Thanks for JetBrains for sponsoring IntelliJ IDEA license for open-source development

jetbrains logos

License

Copyright 2016 Piotr Wittchen

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Comments
  • Connectivity return incorrect results ?

    Connectivity return incorrect results ?

    OS: Android 7.0 Emulator: Nexus S - Nougat API 24

    When I turn off wifi on my phone, I return the result: connectivity.isAvailable() == true

    It happens when turn on/off Wifi on phone several times.

    ReactiveNetwork.observeNetworkConnectivity(this)
                    .subscribeOn(Schedulers.io())
                    .observeOn(Schedulers.newThread())
                    .subscribe(new Consumer<Connectivity>() {
                        @Override public void accept(final Connectivity connectivity) {
                            EventBus.getDefault().post(new NetworkEvent(connectivity.isAvailable()));
                        }
                    });
    
    opened by chihung93 17
  • Update protocol to https for DEFAULT_HOST in WalledGardenInternetObservingStrategy

    Update protocol to https for DEFAULT_HOST in WalledGardenInternetObservingStrategy

    See issue mentioned here: https://github.com/pwittchen/ReactiveNetwork/issues/299#issuecomment-462904722

    Line in the code: https://github.com/pwittchen/ReactiveNetwork/blob/40b725013b8412289f56fec2601c4cab3f0fc76f/library/src/main/java/com/github/pwittchen/reactivenetwork/library/rx2/internet/observing/strategy/WalledGardenInternetObservingStrategy.java#L41

    It needs to be verified and tested before pushing.

    enhancement 
    opened by pwittchen 13
  • Crash OnErrorNotImplementedException

    Crash OnErrorNotImplementedException

    io.reactivex.exceptions.OnErrorNotImplementedException: 
      at io.reactivex.internal.functions.Functions$OnErrorMissingConsumer.accept(Functions.java:704)
      at io.reactivex.internal.functions.Functions$OnErrorMissingConsumer.accept(Functions.java:701)
      at io.reactivex.internal.observers.LambdaObserver.onError(LambdaObserver.java:74)
      at io.reactivex.internal.observers.LambdaObserver.onNext(LambdaObserver.java:64)
      at io.reactivex.internal.operators.observable.ObservableObserveOn$ObserveOnObserver.drainNormal(ObservableObserveOn.java:200)
      at io.reactivex.internal.operators.observable.ObservableObserveOn$ObserveOnObserver.run(ObservableObserveOn.java:252)
      at io.reactivex.android.schedulers.HandlerScheduler$ScheduledRunnable.run(HandlerScheduler.java:109)
      at android.os.Handler.handleCallback(Handler.java:751)
      at android.os.Handler.dispatchMessage(Handler.java:95)
      at android.os.Looper.loop(Looper.java:154)
      at android.app.ActivityThread.main(ActivityThread.java:6692)
      at java.lang.reflect.Method.invoke(Native Method:0)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
    Caused by: android.view.WindowManager$BadTokenException: 
      at android.view.ViewRootImpl.setView(ViewRootImpl.java:890)
      at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
      at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:97)
      at android.app.Dialog.show(Dialog.java:538)
      at com.hung.nc.MyApplication$1.accept(MyApplication.java:93)
      at com.hung.nc.MyApplication$1.accept(MyApplication.java:75)
      at io.reactivex.internal.observers.LambdaObserver.onNext(LambdaObserver.java:60)
    
    private void initConnectivity() {
            internetDisposable = ReactiveNetwork.observeInternetConnectivity(5000, "www.google.com", 80, 10000)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean isConnectedToInternet) {
                            if (isConnectedToInternet) {
                                if (!FavoriteManager.getInstance().hasSynchronized()) {
                                    FavoriteManager.getInstance().synchronizeFavorites(true, null);
                                }
                                if (appStateMonitor.isAppInForeground()) {
                                    if (errorInternet != null) {
                                        if (errorInternet.isShowing()) {
                                            errorInternet.dismiss();
                                        }
                                    }
                                }
                            } else {
                                if (appStateMonitor.isAppInForeground() && ContextHelper.getMainActivity() != null) {
                                    if (errorInternet == null) {
                                        errorInternet = AlertUtil.dialogError(ContextHelper.getMainActivity(), ResourceUtil.getString(R.string.error_internet), null);
                                        errorInternet.show();
                                    } else if (!errorInternet.isShowing()) {
                                        errorInternet.show();
                                    }
                                }
                            }
                        }
                    });
        }
    
     @Override
        public void onAppDidEnterBackground() {
            safelyDispose(internetDisposable);
        }
    
        private void safelyDispose(Disposable... disposables) {
            for (Disposable subscription : disposables) {
                if (subscription != null && !subscription.isDisposed()) {
                    subscription.dispose();
                }
            }
        }
    

    Tks .

    RxJava2.x 
    opened by chihung93 13
  • Switching off Wifi yields false positive DISCONNECTED

    Switching off Wifi yields false positive DISCONNECTED

    First of all I think this is a really great library and I'd really want to use it in our app. Unfortunately I've found an issue while playing around with it on my Sony Xperia Z2 running Android 6.0.1. The issue is also reproducible for me with the supplied java test app: screenshot

    There have actually been instances where it worked. I guess mostly on a fresh app start and switching off Wifi for the first time, but after that I got stuck at a DISCONNECTED state, where typeName sometimes states NONE and sometimes MOBILE

    bug 
    opened by Bombo 13
  • Unregister receiver crash for Pre-Lollipop devices

    Unregister receiver crash for Pre-Lollipop devices

    Got a crash on an Asus Transformer (API 16) when rotating the device. I unsubscribe in onPause and subscribe in onResume but I think there's a problem unregistering the receiver if it's not attached.

    I have a subscription from it to a BehaviourSubject and multiple subscriptions from the BehaviourSubject to other subscribers.

    09-29 11:04:31.350 1174-1174/uk.co.imagitech.learn2.hp E/ActivityThread: Activity uk.co.imagitech.learn2.hp.MainActivity has leaked IntentReceiver com.github.pwittchen.reactivenetwork.library.network.observing.strategy.PreLollipopNetworkObservingStrategy$1$1@416c8ad0 that was originally registered here. Are you missing a call to unregisterReceiver()?
         android.app.IntentReceiverLeaked: Activity uk.co.imagitech.learn2.hp.MainActivity has leaked IntentReceiver com.github.pwittchen.reactivenetwork.library.network.observing.strategy.PreLollipopNetworkObservingStrategy$1$1@416c8ad0 that was originally registered here. Are you missing a call to unregisterReceiver()?
             at android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:792)
             at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:593)
             at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1120)
             at android.app.ContextImpl.registerReceiver(ContextImpl.java:1107)
             at android.app.ContextImpl.registerReceiver(ContextImpl.java:1101)
             at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:365)
             at com.github.pwittchen.reactivenetwork.library.network.observing.strategy.PreLollipopNetworkObservingStrategy$1.call(PreLollipopNetworkObservingStrategy.java:50)
             at com.github.pwittchen.reactivenetwork.library.network.observing.strategy.PreLollipopNetworkObservingStrategy$1.call(PreLollipopNetworkObservingStrategy.java:42)
             at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
             at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
             at rx.Observable.unsafeSubscribe(Observable.java:10150)
             at rx.internal.operators.OperatorSubscribeOn$1.call(OperatorSubscribeOn.java:94)
             at rx.internal.schedulers.CachedThreadScheduler$EventLoopWorker$1.call(CachedThreadScheduler.java:228)
             at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
             at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:442)
             at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
             at java.util.concurrent.FutureTask.run(FutureTask.java:137)
             at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:150)
             at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:264)
             at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
             at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
             at java.lang.Thread.run(Thread.java:856)
    09-29 11:04:31.360 1174-1174/uk.co.imagitech.learn2.hp E/AndroidRuntime: FATAL EXCEPTION: main
         java.lang.IllegalStateException: Fatal Exception thrown on Scheduler.Worker thread.
             at rx.android.schedulers.LooperScheduler$ScheduledAction.run(LooperScheduler.java:114)
             at android.os.Handler.handleCallback(Handler.java:615)
             at android.os.Handler.dispatchMessage(Handler.java:92)
             at android.os.Looper.loop(Looper.java:137)
             at android.app.ActivityThread.main(ActivityThread.java:4745)
             at java.lang.reflect.Method.invokeNative(Native Method)
             at java.lang.reflect.Method.invoke(Method.java:511)
             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
             at dalvik.system.NativeStart.main(Native Method)
          Caused by: java.lang.IllegalArgumentException: Receiver not registered: com.github.pwittchen.reactivenetwork.library.network.observing.strategy.PreLollipopNetworkObservingStrategy$1$1@416c8ad0
             at android.app.LoadedApk.forgetReceiverDispatcher(LoadedApk.java:654)
             at android.app.ContextImpl.unregisterReceiver(ContextImpl.java:1143)
             at android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:378)
             at com.github.pwittchen.reactivenetwork.library.network.observing.strategy.PreLollipopNetworkObservingStrategy$1$2.call(PreLollipopNetworkObservingStrategy.java:54)
             at com.github.pwittchen.reactivenetwork.library.network.observing.strategy.PreLollipopNetworkObservingStrategy$2$1.call(PreLollipopNetworkObservingStrategy.java:71)
             at rx.android.schedulers.LooperScheduler$ScheduledAction.run(LooperScheduler.java:107)
             at android.os.Handler.handleCallback(Handler.java:615) 
             at android.os.Handler.dispatchMessage(Handler.java:92) 
             at android.os.Looper.loop(Looper.java:137) 
             at android.app.ActivityThread.main(ActivityThread.java:4745) 
             at java.lang.reflect.Method.invokeNative(Native Method) 
             at java.lang.reflect.Method.invoke(Method.java:511) 
             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
             at dalvik.system.NativeStart.main(Native Method) 
    
    bug 
    opened by Kisty 13
  • State CONNECTED sometimes is not returned when wifi is turned off while having mobile internet connection (Android 9)

    State CONNECTED sometimes is not returned when wifi is turned off while having mobile internet connection (Android 9)

    Describe the bug I use below code for tract network connection in application. It working well on my Android 8 device but it some time not working well on my Android 9 when I try to switch between wifi and mobile internet (4G)

    ReactiveNetwork
                    .observeNetworkConnectivity(context)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({
                        Log.i("ReactiveNetwork", "connect " + it)
                    }, {
                        Log.i("ReactiveNetwork", "error " + it)
                    })
    

    To Reproduce

    • I open app without wifi and mobile connection (below log line 1 display)
    • I turn on wifi (below log line 2 display)
    • I turn on mobile (no log display)
    • I turn off wifi (below log line 3 + 4 display)
    • I turn on wifi (no log display)
    • I turn off wifi (below log line 5 display). At this time, my phone still have mobile connection but status CONECT never return (I wait for 2 -> 10 minutes). I tested this many time.

    And here is the log

    2019-05-02 11:02:36.426 24510-24510/ I/ReactiveNetwork: connect Connectivity{state=DISCONNECTED, detailedState=IDLE, type=-1, subType=-1, available=false, failover=false, roaming=false, typeName='NONE', subTypeName='NONE', reason='', extraInfo=''}
    2019-05-02 11:02:44.812 24510-24510/ I/ReactiveNetwork: connect Connectivity{state=CONNECTED, detailedState=CONNECTED, type=1, subType=0, available=true, failover=false, roaming=false, typeName='WIFI', subTypeName='', reason='null', extraInfo='null'}
    2019-05-02 11:03:01.641 24510-24510/ I/ReactiveNetwork: connect Connectivity{state=DISCONNECTED, detailedState=IDLE, type=-1, subType=-1, available=false, failover=false, roaming=false, typeName='NONE', subTypeName='NONE', reason='', extraInfo=''}
    2019-05-02 11:03:01.777 24510-24510/ I/ReactiveNetwork: connect Connectivity{state=CONNECTED, detailedState=CONNECTED, type=0, subType=13, available=true, failover=false, roaming=false, typeName='MOBILE', subTypeName='LTE', reason='connected', extraInfo='diginet'}
    2019-05-02 11:03:15.958 24510-24510/ I/ReactiveNetwork: connect Connectivity{state=DISCONNECTED, detailedState=IDLE, type=-1, subType=-1, available=false, failover=false, roaming=false, typeName='NONE', subTypeName='NONE', reason='', extraInfo=''}
    

    Expected behavior state CONNECTED should return

    Smartphone (please complete the following information):

    • Device: Xiaomi A2 (android 9), One Plus 5T(android 9), Huawei Y9 (android 8)
    • OS: Android 9, Android 8
    • Library Version: 3.0.2

    Let me know if you need more information. Thank you

    bug 
    opened by PhanVanLinh 12
  • Problem when receiving internet connectivity in Android P (API 28)

    Problem when receiving internet connectivity in Android P (API 28)

    Hi guys! Great job with this lib!

    I just wanted to report a small issue that I'm having while receiving internet connectivity.

    I'm using the following:

            return ReactiveNetwork.observeInternetConnectivity(InternetObservingSettings
                    .initialInterval(DEFAULT_INITIAL_PING_INTERVAL_IN_MS)
                    .interval(DEFAULT_PING_INTERVAL_IN_MS)
                    .host(DEFAULT_PING_HOST)
                    .port(DEFAULT_PING_PORT)
                    .timeout(DEFAULT_PING_TIMEOUT_IN_MS)
                    .errorHandler(errorHandler)
                    .build());
    

    This is always returning false, but just in Android P. Any other version works fine.

    I read about Android P is restricting network status access and I'm not sure if there can be a problem related to that, what do you guys think? Have any of you found a similar issue and respective solution?

    Thanks in advance!

    opened by danielbeleza 11
  • Add check internet connectivity immediately

    Add check internet connectivity immediately

    This is so that the app checks for connection immediately instead of delaying the check. See http://reactivex.io/RxJava/javadoc/rx/Observable.html#interval(long,%20long,%20java.util.concurrent.TimeUnit)

    enhancement 
    opened by Kisty 11
  • Migrate to RxJava 3

    Migrate to RxJava 3

    This PR introduces the following update: support for RxJava 3 (potentially closing #365 ).

    I wanted to use ReactiveNetwork in a new project that targets RxJava 3, so I figured I might as well make the transition myself.

    A few major things have changed:

    • I have changed the package name to "rx3".
    • The Build Tools are now on "29.0.2" to support the new Gradle plugin in Android Studio 4.
    • Gradle version is now at "6.3".
    • The onError method of the NetworkObservingStrategy interface is now using a Throwable instead of a simple Exception. This had to be changed because a lot of methods inside the various implementations of the interface can throw a generic Throwable.
    • The android.enableUnitTestBinaryResources has been removed because it is no longer supported.

    The rest of the changes are just related to the new version of RxJava (mainly changing the package references).

    All unit tests pass, all code styles checks pass. Both example apps work perfectly (I had to add the Java compatibility option to the Kotlin app to make it build). The build on Travis works.

    Please, let me know if you're interested in merging this PR and, if so, what would be the next steps.

    RxJava3.x 
    opened by MrAsterisco 10
  • Check Server is online or not [NOT WORKING]

    Check Server is online or not [NOT WORKING]

    Server Online or Not it is always returning false in connectivity no matter what.

    To Reproduce Here is concise function i wrote to check if server is online or not. which is not working

    public void observeServerURL(){
          String urlString = "http://www.someserver.com";
    
          if(urlString == null || urlString.isEmpty())return;
          InternetObservingSettings settings = InternetObservingSettings.builder()
                  .strategy(new SocketInternetObservingStrategy())
                  .host(urlString)
                  .timeout(2000)
                  .interval(10 * 1000) // each 10 seconds
                  .initialInterval(1000)
                  .build();
                  ReactiveNetwork
                          .observeInternetConnectivity(settings)
                          .subscribeOn(Schedulers.io())
                          .observeOn(AndroidSchedulers.mainThread())
                          .subscribe(
                                  isOnline -> {
                                      LogUtils.d("checking URL status:"+urlString+" , its online:"+isOnline);
                                      }
                                  },
                                  Throwable::printStackTrace
                          );
    }
    

    Smartphone (please complete the following information):

    • Device: OPPO
    • OS: 5.1
    • Library Version: 3.0.2
    opened by Zulqurnain 10
  • Possible memory leak

    Possible memory leak

    https://github.com/pwittchen/ReactiveNetwork/blob/RxJava2.x/library/src/main/java/com/github/pwittchen/reactivenetwork/library/rx2/network/observing/strategy/PreLollipopNetworkObservingStrategy.java#L70

    unregisterReceiver never be called. So, BroadcastReceiver will be leaked. I've tried to set up break point on this line and this was not called, howerer I disposed my Disposable.

    bug 
    opened by lion4ik 10
  • ReactiveNetwork(RN) usage of IPv6 and DNS results prioritization

    ReactiveNetwork(RN) usage of IPv6 and DNS results prioritization

    Hi, I would like to understand RN usage on IPv4 and IPv6 since I can't find in any documentation regarding this. More specifically, I would like to know:

    • Does RN officially support IPv6?
    • Does RN prioritize the use of IPv4 over IPv6?
    • Is it possible to configure IPv4 over IPv6?

    The goal is to prioritize the use of IPv4 since it provides a more stable experience.

    Any information will be appreciated! Thanks,

    question 
    opened by yifeifiona 1
  • Internet connectivity issue: Could not establish connection with WalledGardenStrategy

    Internet connectivity issue: Could not establish connection with WalledGardenStrategy

    Internet connected state is misleading I added the library to my projects and I'm only observing internet connectivity. It is always returning false even when my wifi is working fine. To confirm that, I observed network state and it is returning CONNECTED while internet connectivity is showing false.

    To Reproduce Steps to reproduce the behavior:

    1. I just tested the Kotlin sample nothing fancy

    Expected behavior It should show that internet is connected while Network state is CONNECTED

    Screenshots If applicable, add screenshots to help explain your problem.

    Smartphone:

    • Device: Xaiomi Pocco F3
    • OS: Android 12
    • Library Version: v3.0.8-rx2

    Error

    I'm continuously getting the following error after each 2 seconds. It seems the library is pinging a URL that is http (Not permitted).

    E/ReactiveNetwork: Could not establish connection with WalledGardenStrategy
        java.io.IOException: Cleartext HTTP traffic to clients3.google.com not permitted
            at com.android.okhttp.HttpHandler$CleartextURLFilter.checkURLPermitted(HttpHandler.java:127)
            at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:462)
            at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:411)
            at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:542)
            at com.github.pwittchen.reactivenetwork.library.rx2.internet.observing.strategy.WalledGardenInternetObservingStrategy.isConnected(WalledGardenInternetObservingStrategy.java:109)
            at com.github.pwittchen.reactivenetwork.library.rx2.internet.observing.strategy.WalledGardenInternetObservingStrategy$1.apply(WalledGardenInternetObservingStrategy.java:66)
            at com.github.pwittchen.reactivenetwork.library.rx2.internet.observing.strategy.WalledGardenInternetObservingStrategy$1.apply(WalledGardenInternetObservingStrategy.java:64)
            at io.reactivex.internal.operators.observable.ObservableMap$MapObserver.onNext(ObservableMap.java:57)
            at io.reactivex.internal.operators.observable.ObservableInterval$IntervalObserver.run(ObservableInterval.java:82)
            at io.reactivex.Scheduler$PeriodicDirectTask.run(Scheduler.java:532)
            at io.reactivex.Scheduler$Worker$PeriodicTask.run(Scheduler.java:479)
            at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:66)
            at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:57)
            at java.util.concurrent.FutureTask.run(FutureTask.java:266)
            at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
            at java.lang.Thread.run(Thread.java:920)
    
    opened by mirwisek 1
  • MarshmallowNetworkObservingStrategy.java line 80

    MarshmallowNetworkObservingStrategy.java line 80

    The bug is reproduce only on 11 android when call ReactiveNetwork.observeNetworkConnectivity(context)

    https://android-review.googlesource.com/c/platform/frameworks/base/+/1758029/

    In ExoPlayer it is fixed like this https://github.com/google/ExoPlayer/commit/2e21208f639c7eb5baf5e7a3ae1180b13be3b733

    android.net.ConnectivityManager.registerNetworkCallback (ConnectivityManager.java:4564) com.github.pwittchen.reactivenetwork.library.rx2.network.observing.strategy.MarshmallowNetworkObservingStrategy.observeNetworkConnectivity (MarshmallowNetworkObservingStrategy.java:80) com.github.pwittchen.reactivenetwork.library.rx2.ReactiveNetwork.observeNetworkConnectivity (ReactiveNetwork.java:92) com.github.pwittchen.reactivenetwork.library.rx2.ReactiveNetwork.observeNetworkConnectivity (ReactiveNetwork.java:73)

    Could you please catch this exception in library? Thanks.

    bug 
    opened by agarajaev 4
  • java.lang.IllegalArgumentException: Too many NetworkRequests filed in Android Nougat(7.1.1).

    java.lang.IllegalArgumentException: Too many NetworkRequests filed in Android Nougat(7.1.1).

    Describe the bug Occur crash when I call the function checkInternetConnectivity(). This is one time issue.

    To Reproduce Steps to reproduce the behavior:

    1. call below function fun checkInternetConnectivity(context: Context): Observable = ReactiveNetwork.observeNetworkConnectivity(context) .flatMapSingle { connectivity -> @Suppress("DEPRECATION") if (connectivity.state() === NetworkInfo.State.CONNECTED) { return@flatMapSingle ReactiveNetwork.checkInternetConnectivity() } Single.fromCallable { false } } .take(1) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread())

    2. Log cat error

    08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: java.lang.IllegalArgumentException: Too many NetworkRequests filed 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.os.Parcel.readException(Parcel.java:1688) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.os.Parcel.readException(Parcel.java:1637) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.net.IConnectivityManager$Stub$Proxy.listenForNetwork(IConnectivityManager.java:2400) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.net.ConnectivityManager.sendRequestForNetwork(ConnectivityManager.java:2856) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.net.ConnectivityManager.registerNetworkCallback(ConnectivityManager.java:3075) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at com.github.pwittchen.reactivenetwork.library.rx2.network.observing.strategy.MarshmallowNetworkObservingStrategy.observeNetworkConnectivity(MarshmallowNetworkObservingStrategy.java:80) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at com.github.pwittchen.reactivenetwork.library.rx2.ReactiveNetwork.observeNetworkConnectivity(ReactiveNetwork.java:92) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at com.github.pwittchen.reactivenetwork.library.rx2.ReactiveNetwork.observeNetworkConnectivity(ReactiveNetwork.java:73) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at com.kakao.i.sdk.agent.util.CommonUtils.checkInternetConnectivity(CommonUtils.kt:1) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at com.kakao.i.sdk.agent.AgentService.checkInternetAndAction(AgentService.kt:1) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at com.kakao.i.sdk.agent.AgentService.checkInternetAndAction$default(AgentService.kt:1) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at com.kakao.i.sdk.agent.AgentService.requestRecognition(AgentService.kt:2) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at com.kakao.i.sdk.agent.AgentService.access$requestRecognition(AgentService.kt:1) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at com.kakao.i.sdk.agent.AgentService$f.a(AgentService.kt:2) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at com.kakao.i.sdk.agent.AgentService$f.invoke(AgentService.kt:1) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at com.kakao.i.sdk.agent.floating.a$a.a(FloatingAgentViewManager.kt:2) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at com.kakao.i.sdk.agent.floating.FloatingAgentView$b.onSingleTapUp(FloatingAgentView.kt:1) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.view.GestureDetector.onTouchEvent(GestureDetector.java:635) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at com.kakao.i.sdk.agent.floating.FloatingAgentView.onTouch(FloatingAgentView.kt:1) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.view.View.dispatchTouchEvent(View.java:10019) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2626) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2307) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.view.View.dispatchPointerEvent(View.java:10243) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4438) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4306) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3853) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3906) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3872) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3999) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3880) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4056) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3853) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3906) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3872) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3880) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3853) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:6246) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:6220) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6181) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:6349) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.os.MessageQueue.nativePollOnce(Native Method) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.os.MessageQueue.next(MessageQueue.java:323) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.os.Looper.loop(Looper.java:136) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at android.app.ActivityThread.main(ActivityThread.java:6119) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at java.lang.reflect.Method.invoke(Native Method) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:982) 08-04 14:00:20.685 5771 5771 E MessageQueue-JNI: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:872) 08-04 14:00:20.691 5771 5771 D AndroidRuntime: Shutting down VM --------- beginning of crash

    Smartphone (please complete the following information):

    • Device: tablet
    • OS: Android 7.1.1
    • Library Version: 3.0.8

    Additional context I think this issue because of only nougat OS like below. https://stackoverflow.com/questions/41957895/android-nougat-too-many-networkrequests-filed

    But I want to protect the crash. So could you please catch this exception in library?

    Thanks.

    bug 
    opened by jonesn123 7
  • Google pixel wifi change event is received in 30 sec delay

    Google pixel wifi change event is received in 30 sec delay

    Describe the bug I am using this code for listening to wifi changes - ReactiveNetwork.observeNetworkConnectivity(context) .subscribeOn(Schedulers.io()) .filter(ConnectivityPredicate.hasType(NetworkCapabilities.TRANSPORT_WIFI)) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ logWarning("###### change network = $it") },{ })

    I am testing the code in different devices and its work, but in Google pixel 3a i am receiving the wifi concavity change event in 30 seconds delay. In Samsung device i am receiving the wifi concavity change event immediately

    To Reproduce Steps to reproduce the behavior:

    1. Turn Off Wifi
    2. Open activity \ fragment that with the specific code
    3. Turn On Wifi in the device
    4. observe subscribe in observeNetworkConnectivity
    5. observe Wifi connection in the Device
    6. See when the Wifi connection success and when observeNetworkConnectivity subscribe received
    7. Wifi connect event received after 30 seconds from the device Wifi connection

    Expected behavior The Wifi connect in the same time

    Smartphone (please complete the following information):

    • Device: Google Pixel 3a
    • OS: Android 11
    • Library Version: 3.0.1
    to verify 
    opened by seladev 5
Releases(v3.0.8-rx2)
  • v3.0.8-rx2(Apr 2, 2020)

    • updated project dependencies
    • update gradle version
    • fixed bug #422 and #415 (changed port for default host for checking internet connectivity from https to http)
    Source code(tar.gz)
    Source code(zip)
  • v3.0.7-rx2(Mar 12, 2020)

  • v0.13.0(Sep 18, 2019)

  • v3.0.6-rx2(Aug 25, 2019)

    • added new method for creating HttpsUrlConnection (HttpsURLConnection createHttpsUrlConnection(final String host, final int port, final int timeoutInMs)) in WalledGardenInternetObservingStrategy, appropriate method is chosen automatically basing on the protocol (http or https) - solves #323
    • note: version 3.0.5 was skipped due to sonatype issues
    Source code(tar.gz)
    Source code(zip)
  • v3.0.4-rx2(Aug 7, 2019)

    • fixed bug #330 - State CONNECTED sometimes is not returned when wifi is turned off while having mobile internet connection (Android 9)
    • fixed bug #307 - Mobile data connection is not active
    • switched default protocol from http to https in WalledGardenInternetObservingStrategy - solves #323
    • added nopen for static code analysis - solves #322
    • bumped project dependencies
    • updated docs
    Source code(tar.gz)
    Source code(zip)
  • v3.0.3-rx2(May 13, 2019)

    • migrated: com.android.support:support-annotations:28.0.0 -> androidx.annotation:annotation:1.0.2 - PR #332
    • migrated com.android.support:appcompat-v7:28.0.0 -> androidx.appcompat:appcompat:1.0.2 - PR #332
    • updated Kotlin to 1.3.31 - PR #332
    • updated RxJava to 2.2.8 - PR #332
    • updated RxAndroid 2.1.1 - PR #332
    • added release.sh script to make release process more automated
    Source code(tar.gz)
    Source code(zip)
  • v3.0.2-rx2(Jan 3, 2019)

  • 3.0.1-rx2(Dec 1, 2018)

    • Fixed unserialized access to subject on Marshmallow - https://github.com/pwittchen/ReactiveNetwork/commit/91b676e726071b2d77b1e26a35dbcafa0fac7b32 by @aperfilyev
    Source code(tar.gz)
    Source code(zip)
  • v3.0.0-rx2(Sep 24, 2018)

    • updated project dependencies
    • updated target SDK
    • simplified codecov.io configuration
    • documented usage of usesClearTextTraffic setting and added it to the sample apps
    • added possibility to configure HTTP response code via httpResponse(int) method in InternetObservingSettings class (API-breaking changes - a few method signatures were changed) - it works for WalledGardenInternetObservingStrategy only
    • updated builder in InternetObservingSettings - removed unused methods
    Source code(tar.gz)
    Source code(zip)
  • v2.1.0-rx2(Aug 5, 2018)

    • bumped project dependencies - PR #292, Commit: https://github.com/pwittchen/ReactiveNetwork/commit/7e4cd4b7e39931d6cceeb0b674ccb506d38f91e4
      • RxJava: 2.1.16 -> 2.2.0
      • Mockito Core: 2.19.1 -> 2.21.0
      • NullAway: 0.4.7 -> 0.5.1
      • Robolectric: 3.1.2 -> 4.0-alpha-3
    Source code(tar.gz)
    Source code(zip)
  • v2.0.0-rx2(Jul 20, 2018)

    • bumped project dependencies -> RxJava: https://github.com/pwittchen/ReactiveNetwork/commit/1d1a301a72d0128548ccf4b9b2cef24c07d38118, others: https://github.com/pwittchen/ReactiveNetwork/commit/597dc03c1c18fb73849c7b0bc4a52d46524bd02b
    • refactored Connectivity class to better builder pattern to improve code consistency (breaking API of the Connectivity class) - PR #283
    • improved unit tests coverage - PR #287
    Source code(tar.gz)
    Source code(zip)
  • v1.0.0(Jun 24, 2018)

    • fixed docs in https://github.com/pwittchen/ReactiveNetwork/commit/76ab2b23210207d83250da5d8fd0cd6e275e3f08 after reporting problem in #276 (returning false-positive connectivity results in one edge-case)
    • updated project dependencies - PR #269, commit 02449af2f38ac463e1aa8824beee46ea823fd83b
    • refactored ReactiveNetwork class with Builder pattern - PR #279
    • removed the following methods from the ReactiveNetwork class:
    Observable<Boolean> observeInternetConnectivity(int interval, String host, int port, int timeout)
    Observable<Boolean> observeInternetConnectivity(int initialIntervalInMs, int intervalInMs, String host, int port, int timeout)
    Observable<Boolean> observeInternetConnectivity(final int initialIntervalInMs, final int intervalInMs, final String host, final int port, final int timeoutInMs, final ErrorHandler errorHandler)
    Observable<Boolean> observeInternetConnectivity(final InternetObservingStrategy strategy)
    Observable<Boolean> observeInternetConnectivity(final InternetObservingStrategy strategy, final String host)
    
    Single<Boolean> checkInternetConnectivity(InternetObservingStrategy strategy)
    Single<Boolean> checkInternetConnectivity(String host,int port, int timeoutInMs)
    Single<Boolean> checkInternetConnectivity(String host, int port, int timeoutInMs, ErrorHandler errorHandler)
    Single<Boolean> checkInternetConnectivity(final InternetObservingStrategy strategy, final String host)
    
    • added InternetObservingSettings class
    • added the following methods to the ReactiveNetwork class:
    Observable<Boolean> observeInternetConnectivity(InternetObservingSettings settings)
    Single<Boolean> checkInternetConnectivity(InternetObservingSettings settings)
    
    Source code(tar.gz)
    Source code(zip)
  • v0.12.4(Jun 24, 2018)

  • 0.12.3(Feb 11, 2018)

    • bumped RxJava: 1.3.3 -> 1.3.5
    • updated Gradle Build Tools: 3.0.0 -> 3.0.1
    • added script for publishing JavaDoc on gh-pages
    • added script for publishing documentation on gh-pages
    Source code(tar.gz)
    Source code(zip)
  • v0.12.3-rx2(Jan 3, 2018)

    • updated project dependencies -> see: https://github.com/pwittchen/ReactiveNetwork/commit/abc1fd5e7f18e3fa504e071f000ae5067946c68f
    • updated gradle configuration in config/quality.gradle (replaced deprecated invocations with new ones)
    Source code(tar.gz)
    Source code(zip)
  • 0.12.2(Nov 12, 2017)

  • v0.12.2-rx2(Nov 11, 2017)

    • updated API of MarshmallowNetworkObservingStrategy
      • made void registerIdleReceiver(context) protected
      • made boolean isIdleMode(context) protected
      • made tryToUnregisterCallback(ConnectivityManager) protected
      • made tryToUnregisterReceiver(context) protected
      • made NetworkCallback createNetworkCallback(context) protected
      • added BroadcastReceiver createIdleBroadcastReceiver()
      • added onNext(Connectivity connectivity)
      • added MarshmallowNetworkObservingStrategy() constructor
      • extracted String messages into protected static final fields
    • set min sdk version for sample apps to 14
    • updated Gradle v. 3.0.0.
    • updated compile sdk version: 25 -> 26
    • updated build tools version: 25.0.2 - > 26.0.2
    • updated kotlin version: 1.1.3-2 -> 1.1.51
    • updated project dependencies
      • RxJava 2.1.2 -> 2.1.6
      • support-annotations: 25.3.0 -> 27.0.1
      • appcompat-v7: 25.3.0 -> 27.0.1
      • truth: 0.34 -> 0.36
      • mockito-core: 2.8.47 -> 2.12.0
    • added ErrorProne for static code analysis
    • added NullAway for static code analysis
    Source code(tar.gz)
    Source code(zip)
  • v0.12.1-rx2(Sep 2, 2017)

  • v0.12.0-rx2(Aug 30, 2017)

    • Fixed NPE occuring when ConnectivityManager is null in ReactiveNetwork.observeNetworkConnectivity() method - issue #209
    • Added new methods to the API for checking Internet connectivity - issue #205
      • Observable<Boolean> observeInternetConnectivity(strategy, host)
      • Single<Boolean> checkInternetConnectivity(strategy, host)
    • Added to documentation comment about monitoring Internet connectivity with custom host - issue #204
    • Classes which implement InternetObservingStrategy handle custom hosts with and without http:// or https:// prefix gracefully - issue #206
    • organized packages with unit tests
    • made the library more hermetic
    • changed visibility of SocketInternetObservingStrategy#isConnected(String host, int port, int timeoutInMs, ErrorHandler handler) method from public to protected
    • changed visibility of SocketInternetObservingStrategy#isConnected(Socket socket, String host, int port, int timeoutInMs, ErrorHandler errorHandler) method from public to protected
    • changed visibility of Connectivity#create(Context, ConnectivityManager) method from public to protected
    • changed visibility of WalledGardenInternetObservingStrategy#isConnected(String host, int port, int timeoutInMs, ErrorHandler errorHandler) method from public to protected
    • changed visibility of WalledGardenInternetObservingStrategy#createHttpUrlConnection(String host, int port, int timeoutInMs) method from public to protected
    Source code(tar.gz)
    Source code(zip)
  • v0.12.0(Aug 30, 2017)

    • Fixed NPE occuring when ConnectivityManager is null in ReactiveNetwork.observeNetworkConnectivity() method - issue #209
    • Added new method to the API for checking Internet connectivity - issue #205
      • Observable<Boolean> observeInternetConnectivity(strategy, host)
    • Added to documentation comment about monitoring Internet connectivity with custom host - issue #204
    • Classes which implement InternetObservingStrategy handle custom hosts with and without http:// or https:// prefix gracefully - issue #206
    • organized packages with unit tests
    • made the library more hermetic
    • changed visibility of SocketInternetObservingStrategy#isConnected(String host, int port, int timeoutInMs, ErrorHandler handler) method from public to protected
    • changed visibility of SocketInternetObservingStrategy#isConnected(Socket socket, String host, int port, int timeoutInMs, ErrorHandler errorHandler) method from public to protected
    • changed visibility of Connectivity#create(Context, ConnectivityManager) method from public to protected
    • changed visibility of WalledGardenInternetObservingStrategy#isConnected(String host, int port, int timeoutInMs, ErrorHandler errorHandler) method from public to protected
    • changed visibility of WalledGardenInternetObservingStrategy#createHttpUrlConnection(String host, int port, int timeoutInMs) method from public to protected
    Source code(tar.gz)
    Source code(zip)
  • v0.11.0-rx2(Aug 5, 2017)

    • added WalledGardenInternetObservingStrategy - fixes #116
    • made WalledGardenInternetObservingStrategy a default strategy for checking Internet connectivity
    • added documentation for NetworkObservingStrategy - solves #197
    • added documentation for InternetObservingStrategy - solves #198
    • fixed package name in AndroidManifest.xml file - solves #195
    • bumped RxJava2 version to 2.1.2
    • bumped Kotlin version to 1.1.3-2
    • bumped Gradle Android Tools version to 2.3.3
    • bumped Retrolambda to 3.7.0
    • increased code coverage with unit tests
    Source code(tar.gz)
    Source code(zip)
  • v0.11.0(Aug 5, 2017)

    • added WalledGardenInternetObservingStrategy - fixes #116
    • made WalledGardenInternetObservingStrategy a default strategy for checking Internet connectivity
    • added documentation for NetworkObservingStrategy - solves #197
    • added documentation for InternetObservingStrategy - solves #198
    • bumped Kotlin version to 1.1.3-2
    • bumped Gradle Android Tools version to 2.3.3
    • bumped Retrolambda to 3.7.0
    Source code(tar.gz)
    Source code(zip)
  • v0.10.0-rx2(Jul 18, 2017)

    • bumped RxJava2 version to 2.1.1
    • bumped test dependencies
    • created Code of Conduct
    • updated unit tests
    • updated Kotlin version in sample apps
    • added retrolambda to the sample Java app - issue #163
    • fixed behavior of network observing in disconnected state - issue #159
    • added the following methods to ReactiveNetwork class:
      • Single<Boolean> checkInternetConnectivity()
      • Single<Boolean> checkInternetConnectivity(InternetObservingStrategy strategy)
      • Single<Boolean> checkInternetConnectivity(String host, int port, int timeoutInMs)
      • Single<Boolean> checkInternetConnectivity(String host, int port, int timeoutInMs, ErrorHandler errorHandler)
      • Single<Boolean> checkInternetConnectivity(InternetObservingStrategy strategy, String host, int port, int timeoutInMs, ErrorHandler errorHandler)
    Source code(tar.gz)
    Source code(zip)
  • v0.10.0(Jul 18, 2017)

    • bumped RxJava1 version to 1.3.0
    • bumped test dependencies
    • created Code of Conduct
    • updated Kotlin version in sample apps
    • added retrolambda to the sample Java app - issue #163
    • fixed behavior of network observing in disconnected state - issue #159
    Source code(tar.gz)
    Source code(zip)
  • v0.9.1-rx2(Apr 30, 2017)

    • updated ConnectivityPredicate and replaced io.reactivex.functions.Function with io.reactivex.functions.Predicate to make it compatible with RxJava2 filtering methods #168
    • bumped RxJava2.x version to 2.1.0
    Source code(tar.gz)
    Source code(zip)
  • v0.9.1(Apr 30, 2017)

  • v0.9.0-rx2(Apr 11, 2017)

    • migrated library to RxJava2.x on RxJava2.x branch and released it as reactivenetwork-rx2 artifact
    • updated dependencies
    • updated documentation
    • updated sample apps
    Source code(tar.gz)
    Source code(zip)
  • v0.9.0(Apr 11, 2017)

    • migrated library to RxJava2.x on RxJava2.x branch and released it as reactivenetwork-rx2 artifact
    • updated dependencies
    • updated documentation
    • updated sample apps
    Source code(tar.gz)
    Source code(zip)
  • v0.8.0(Feb 12, 2017)

    • renamed DefaultInternetObservingStrategy to SocketInternetObservingStrategy class
    • added observeInternetConnectivity(InternetObservingStrategy) method to ReactiveNetwork class
    • removed DefaultInternetObservingStrategy#ON_CLOSE_SOCKET_ERROR_MSG static field
    • added permission annotations
    • updated Connectivity class. Now it contains the following fields with getters: state, detailedState, type, subType, available, failover, roaming, typeName, subTypeName, reason, extraInfo (it's wrapped data of NetworkInfo class from Android SDK)
    • added Builder to the Connectivity class
    • created ConnectivityPredicate class
    • methods Func1<Connectivity, Boolean> hasState(final NetworkInfo.State... states) and Func1<Connectivity, Boolean> hasType(final int... types) were moved from Connectivity class to ConnectivityPredicate class
    • updated Gradle and Travis configuration
    • updated project dependencies
    Source code(tar.gz)
    Source code(zip)
  • v0.7.0(Dec 10, 2016)

    • added isConnected(final String host, final int port, final int timeoutInMs, ErrorHandler errorHandler) method to DefaultInternetObservingStrategy class
    • added isConnected(final Socket socket, final String host, final int port, final int timeoutInMs, final ErrorHandler errorHandler) method to DefaultInternetObservingStrategy class
    • renamed SocketErrorHandler to ErrorHandler and updated its API
    • renamed DefaultSocketErrorHandler to DefaultErrorHandler
    • updated API of the InternetObservingStrategy
    • updated packages organization
    • migrated unit tests to Robolectric (now tests can be executed without an emulator or a device)
    • enabled test coverage reports with codecov.io and Jacoco
    • test coverage was increased from 54% to 74%
    • unit tests are now executed on Travis CI
    • test coverage report is generated by Travis CI with codecov.io
    • added MarshmallowNetworkObservingStrategy and handling Doze mode
    • bumped RxJava to v. 1.2.3
    • updated build tools to v. 2.0.3
    • updated Gradle configuration
    • updated Travis CI configuration
    • added ProGuard configuration
    Source code(tar.gz)
    Source code(zip)
Owner
Piotr Wittchen
I edit text files for a living
Piotr Wittchen
Practice on connecting to internet and getting data from internet app. This gets Mars photos

MarsPhotos - Starter Code Starter code for Android Basics in Kotlin. Introduction Using this stater code you will create MarsPhotos is a demo app that

Espérant GADA 0 Nov 6, 2021
A small Android project to practice executing network requests and parsing the network response

InspirationalQuotesExercise A small Android project to practice executing network requests and parsing the network response This app uses the ZenQuote

Caren 0 Oct 13, 2021
No Internet Layout Library 2.5 0.0 Java #layout #check_internet

No Internet Layout Library Library to check internet connection and change layout to no internet layout if there is no internet. Gradle: allprojects {

Mohamed Wessam 116 Dec 20, 2022
Starter code for getting and saving data from the Internet using Kotlin.

Doggos Description Doggos is an app that fetches (pun intended) information from a third party API. The API returns data about a random dog that conta

Latifah President 0 Nov 4, 2021
CheckInternetConnection - CheckInternetConnection helps to find out if user`s Android device is connected to Internet or not

Check Internet Connection CheckInternetConnection helps to find out if user`s An

Hamed.D 1 Jan 16, 2022
Practice parsing data from the internet

InspirationalQuotesExercise A small Android project to practice executing network requests and parsing the network response This app uses the ZenQuote

Ayana Bando 0 Oct 19, 2021
consumo de internet cortesia de google developers

MarsRealEstateFinal - Solution Code Solution code for Android Kotlin Fundamentals Codelab 8.3 Filtering and detail views with internet data. Introduct

null 0 Nov 3, 2021
WideFi - Internet sharing without Root

widefi Internet sharing without Root What Share your Android device's Internet connection with other devices without needing Root. WideFi works by cre

pyamsoft 18 Dec 28, 2022
An App to download a file from Internet by clicking on a custom-built button

LoadApp LoadApp is an app to download a file from the Internet by clicking on a custom-built button where: Width of the button gets animated from left

Anas Tariq 2 Aug 29, 2022
SimpleApiCalls is a type-safe REST client for Android. The library provides the ability to interact with APIs and send network requests with HttpURLConnection.

SimpleApiCalls ?? SimpleApiCalls is a type-safe REST client for Android. The library provides the ability to interact with APIs and send network reque

null 4 Nov 28, 2022
Android network client based on Cronet. This library let you easily use QUIC protocol in your Android projects

Android network client based on Cronet. This library let you easily use QUIC protocol in your Android projects

VK.com 104 Dec 12, 2022
Observe Android's CONNECTIVITY_CHANGE broadcasts using RxJava.

Rx.Network Listen for Android's CONNECTIVITY_CHANGE broadcasts. Use Add the ACCESS_NEWORK_STATE permission to AndroidManifest.xml <uses-permission

Andrefio 23 Jul 7, 2022
A library that observes your network status.

A library that observes your network status. Update in progress ... Download Using gradle In your root build.gradle at the end of repositories add all

Moses Wangira 9 Apr 18, 2022
Compact and easy to use, 'all-in-one' android network solution

Deprecated Unfortunately due to many reasons including maintenance cost, this library is deprecated. I recommend to use Retrofit/OkHttp instead. Curre

Orhan Obut 585 Dec 30, 2022
Write your asynchronous Network / IO call painlessly in Kotlin !!

Asynkio : Write asynced IO/ Network calls painlessly on android | | | Documentation Write your network requests, IO calls in android with Kotlin seaml

Nikhil Chaudhari 82 Jan 26, 2022
Sandwich was invented for constructing the standardized response interface from the network response

?? A lightweight and standardized Android network response interface for handling successful data and error responses.

Jaewoong Eum 973 Jan 5, 2023
Operations are performed by calling api endpoints over the network

##About The app Operations are performed by calling api endpoints over the network. Local data is in effect immutable, the client just downloads updat

Marc Daniel Registre 1 Oct 22, 2021
Cli lightning network server, based on LDK (rust-lightning). Provides DUMB-RPC interface (telnet friendly).

Hello Lightning Cli lightning network server, based on LDK (rust-lightning). Provides DUMB-RPC interface (telnet friendly). Example: Build it run it:

null 9 Mar 28, 2022