Giter Site home page Giter Site logo

pwittchen / reactivenetwork Goto Github PK

View Code? Open in Web Editor NEW
2.5K 64.0 275.0 1.67 MB

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

Home Page: http://pwittchen.github.io/ReactiveNetwork/docs/RxJava2.x/

License: Apache License 2.0

Java 97.70% Kotlin 1.79% Shell 0.51%
android internet-connection network-connection network-monitoring wifi network internet rxjava rxjava2 rxandroid

reactivenetwork's Introduction

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.

reactivenetwork's People

Contributors

agabrys avatar aperfilyev avatar dependabot-preview[bot] avatar dilongl avatar futtetennista avatar kisty avatar msridhar avatar pwittchen avatar tushar-nallan avatar ychescale9 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

reactivenetwork's Issues

Add backward compatibility for 0.3.0 and appropriate annotations

add observeConnectivity() method back to keep backward compatibility in 0.3.0 and deprecate it. It will be removed in 0.4.0. Other methods like: getConnectivityStatus(context, boolean) and enableInternetCheck are obsolete and no longer valid, so they can be removed. Consider deprecating methods related to WiFi (create a separate library for them first).

Is android.permission.ACCESS_COARSE_LOCATION really needed?

Hi there,

as per subject, is ACCESS_COARSE_LOCATION really needed to be requested by applications using ReactiveNetwork? I've tried to remove it on a custom build of the library and it doesn't seem to cause any ill effects, but maybe I'm missing something here...

Thank you!

Add other network stautuses

Add the following to detect WIFI connectivity status, the same way you did in the NetworkingEvents Library:

WIFI_CONNECTED("connected to WiFi"),
WIFI_CONNECTED_HAS_INTERNET("connected to WiFi (Internet available)"),
WIFI_CONNECTED_HAS_NO_INTERNET("connected to WiFi (Internet not available)"),

for wifi you only have
WIFI_CONNECTED("connected to WiFi")

Release 0.1.4

Initial release notes:

  • bumped RxJava dependency to v. 1.1.0
  • bumped RxAndroid dependency to v. 1.1.0
  • bumped Google Truth test dependency to v. 0.27

Things to do:

  • bump library version
  • upload archives to Maven Central
  • close and release artifact on Maven Central
  • update CHANGELOG.md after Maven Sync
  • bump library version in README.md
  • create new GitHub release

Create GitHub release of 0.0.4 after updating README.md

Initial release notes:

  • added WifiManager.SCAN_RESULTS_AVAILABLE_ACTION to BroadcastReceiver responsible for receiving WiFi access points scan results
  • fixed bug connected with improper work of observeWifiAccessPoints() method reported in issue #8
  • updated sample app

Mobile data loss and 100% loss

Hey man, first off. Thanks for all your hard work. The library is amazing.

I was using your library and i noticed there is something missing. We cannot check mobile data loss nor can we check 100% loss.

Yes, the library detects if there is no internet (airplane mode) or if we do have internet (Wifi connected, internet available and mobile connected) but it would be nice if the following scenarios could be handled as well:

Mobile data loss: eg user is underground and mobile data is loss. Initially i thought that unknown would be used to handle this but it isnt. I had to do it separately.

Here is a code snippet on how i am currently doing it without the library:

/**
 * Determines if there is or if there isnt actual mobile data
 *
 * @return
 */
private boolean hasMobileData() {
    boolean mobileDataEnabled = true; // Assume disabled
    ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
    try {
        Class cmClass = Class.forName(cm.getClass().getName());
        Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
        method.setAccessible(true); // Make the method callable

        // get the setting for "mobile data"
        mobileDataEnabled = (Boolean) method.invoke(cm);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

    Log.e(TAG, "hasMobileData: " + mobileDataEnabled);
    return mobileDataEnabled;
}

Also, the other scenario is when we do not have mobile data but we DO have Wifi and it is on 100% packet loss (can be tested using a Network Link Conditioner). This basically means internet is there, we are connected to Wifi but packets are just not coming in.

Library does not work with Ethernet and other connection types

Thanks for a nice library, it looks very useful! We were about to take this into use, but discovered that because of the implementation our app cannot react to ethernet connections. This makes it unsuitable for use on f.e. Android TV which has a ethernet port and is likely to be connected using this, which is our use case.

One solution might be to add ethernet to the available ConnectivityStatus Enum. Another would be to ignore the network type and observe Android NetworkInfo.State, perhaps as an addition to the existing ConnectivityStatus. In our use cases so far we have only cared about being connected (as indicated by NetworkInfo.State.CONNECTED) or not, ie. a binary state, which could be handled by filtering events as you've already indicated in your README example.

As a third suggestion, it's probably possible to re-use or mirror the different network types in ConnectivityManager, eg. ConnectivityManager.TYPE_WIFI, ConnectivityManager.TYPE_MOBILE instead of creating a separate Enum with the same end result.

Create GitHub release for 0.0.3 after updating README.md

Initial release notes:

  • removed WifiManager.WIFI_STATE_CHANGED_ACTION filter from BroadcastReceiver for observing connectivity (now we're observing only situation when device connects to the network or disconnects from the network - not situation when user turns WiFi on or off)
  • added UNDEFINED element for ConnectivityStatus
  • fixed bug causing emission of the same ConnectivityStatus twice

Release 0.5.0

This release should resolve problem raised in #62.

Initial release notes:

  • handled all connection types (including Ethernet) (issue #71)
  • removed ConnectivityStatus enum and replaced it with Connectivity class.
  • replaced Observable<ConnectivityStatus> observeNetworkConnectivity(final Context context) method with Observable<Connectivity> observeNetworkConnectivity(final Context context)
  • introduced a new way of network monitoring with NetworkCallback available from Android N (API 21) (issue #62)
  • added NetworkObservingStrategy, which allows applying different network monitoring strategies
  • added PreLollipopNetworkObservingStrategy with old network monitoring implementation
  • added LollipopNetworkObservingStrategy with new network monitoring implementation
  • added Observable<Connectivity> observeNetworkConnectivity(final Context context, final NetworkObservingStrategy strategy) method to ReactiveNetwork class
  • made method for creating Observables static like in original RxJava library
  • added create() method to ReactiveNetwork class
  • made constructor of ReactiveNetwork class protected
  • added Preconditions class verifying correctness of the input parameters
  • added more unit tests

Things to be implemented:

  • Use new way of monitoring connectivity introduced in Android N.
  • Keep backward compatibility for "pre-N" devices
  • If possible, create strategy interface for monitoring connectivity and use appropriate implementation basing on system version
  • Allow users to have their own strategy implementations
  • Support all connection types (including Ethernet)

Things to be done for release process:

  • bump library version to 0.5.0
  • upload Archives to Maven Central Repository
  • close and release artifact on Nexus
  • update gh-pages
  • update CHANGELOG.md after Maven Sync
  • remove note about documentation draft
  • bump library version in README.md after Maven Sync
  • create new GitHub release

References:

Update dependencies

  • RxJava needs to be updated to v. 1.1.5
  • RxAndroid needs to be updated to v. 1.2.0
  • Google Truth needs to be updated to v. 0.28

Release v. 0.1.0

Initial release notes:

  • changed UNDEFINED status to UNKNOWN
  • added WIFI_CONNECTED_HAS_INTERNET and WIFI_CONNECTED_HAS_NO_INTERNET statuses
  • added enableInternetCheck() method to ReactiveNetwork object. When it's called, WIFI_CONNECTED_HAS_INTERNET and WIFI_CONNECTED_HAS_NO_INTERNET statuses can occur. Otherwise, only WIFI_CONNECTED can occur.

Release 0.4.0

General draft for the notes:

This release will be dedicated to removing methods for observing WiFi access points and WiFi signal level from the library and reducing number of permissions in AndroidManifest.xml file (mentioned in #50 and #52). This functionality will be extracted to a separate library, which will be mentioned and linked in release notes and README.md file.

Initial release notes:

Removed deprecated methods from the public API:

  • removed depreacted Observable<ConnectivityStatus> observeConnectivity(final Context context) method in favor of Observable<ConnectivityStatus> observeNetworkConnectivity(final Context context) method
  • removed depreacted Observable<List<ScanResult>> observeWifiAccessPoints(final Context context) method in favor of ReactiveWiFi library
  • removed depreacted Observable<WifiSignalLevel> observeWifiSignalLevel(final Context context) method in favor of ReactiveWiFi library
  • removed depreacted Observable<Integer> observeWifiSignalLevel(final Context context,final int numLevels) method in favor of ReactiveWiFi library

Removed permissions in AndroidManifest.xml:

  • removed android.permission.ACCESS_WIFI_STATE permission from AndroidManifest.xml
  • removed android.permission.CHANGE_WIFI_STATE permission from AndroidManifest.xml
  • removed android.permission.ACCESS_COARSE_LOCATION permission from AndroidManifest.xml

Things to do:

  • merge PR #67 to the master branch
  • update documentation for 0.4.0 ➡️ #57
  • bump library version to 0.4.0 ➡️ done in 102065b
  • upload Archives to Maven Central Repository
  • close and release artifact on Nexus
  • update gh-pages ➡️ done in 55dd40c
  • update CHANGELOG.md after Maven Sync
  • bump library version in README.md after Maven Sync
  • create new GitHub release

Release v. 0.1.3

Note: Consider resolving remaining open tasks before releasing new version.

Initial release notes:

  • fixed bug with incorrect status after going back from background inside the sample app reported in issue #31
  • fixed RxJava usage in sample app
  • fixed RxJava usage in code snippets in README.md
  • added static code analysis
  • updated code formatting
  • added sample sample app in Kotlin

Things to do:

  • bump library version
  • upload archives to Maven Central
  • close and release artifact on Maven Central
  • update CHANGELOG.md after Maven Sync
  • bump library version in README.md
  • create new GitHub release

Release 0.3.0

Initial release notes:

  • removed enableInternetCheck() method
  • removed ConnectivityStatus.WIFI_CONNECTED_HAS_INTERNET enum value
  • removed ConnectivityStatus.WIFI_CONNECTED_HAS_NO_INTERNET enum value
  • changed method name from Observable<ConnectivityStatus> observeConnectivity(final Context context) to Observable<ConnectivityStatus> observeNetworkConnectivity(final Context context)
  • deprecated Observable<ConnectivityStatus> observeConnectivity(final Context context) method
  • deprecated Observable<List<ScanResult>> observeWifiAccessPoints(final Context context) method
  • depreceated Observable<WifiSignalLevel> observeWifiSignalLevel(final Context context) method
  • deprecated Observable<Integer> observeWifiSignalLevel(final Context context, final int numLevels) method
  • changed method signature from ConnectivityStatus getConnectivityStatus(final Context context, final boolean checkInternet) to ConnectivityStatus getConnectivityStatus(final Context context)
  • updated ConnectivityStatus getConnectivityStatus(final Context context) method and added JavaDoc for it
  • added Observable<Boolean> observeInternetConnectivity(final int interval, final String host, final int port, final int timeout) method
  • added Observable<Boolean> observeInternetConnectivity() method
  • added android.permission.INTERNET to the AndroidManifest.xml
  • updated JavaDoc
  • updated sample apps
  • updated documentation in README.md
  • bumped RxJava version to 1.1.5
  • bumped RxAndroid version to 1.2.0
  • bumped Google Truth version to 0.28 (test dependency)

Things to do:

  • test and merge PR #64 to the master branch
  • bump library version to 0.3.0 ➡️ done in ac3a61f
  • upload Archives to Maven Central Repository
  • close and release artifact on Nexus
  • update gh-pages
  • update CHANGELOG.md after Maven Sync
  • bump library version in README.md after Maven Sync
  • create new GitHub release

Execute function twice

Hello good library.
I have a problem with the function

new ReactiveNetwork().observeConnectivity(context)
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeOn(Schedulers.io())
    ... // anything else what you can do with RxJava
    .subscribe(new Action1<ConnectivityStatus>() {
      @Override public void call(ConnectivityStatus connectivityStatus) {
        // do something with connectivityStatus
      }
    });

The " // do something with connectivityStatus" is executing twice.
Please you have a solution? Thanks

Release 0.2.0

Initial release notes:

  • added possibility to observe WiFi signal level with observeWifiSignalLevel(context, numLevels) and observeWifiSignalLevel(context) method
  • created WifiSignalLevel enum
  • added internet check to parameters of getConnectivityStatus(context, checkInternet) method
  • made getConnectivityStatus(context, checkInternet) method public
  • changed String variable status in ConnectivityStatus enum to description and made it public
  • changed output of the toString() method in ConnectivityStatus to keep consistency with another enum
  • made ReactiveNetwork class non-final
  • bumped Kotlin version in sample app to 1.0.0-rc-1036
  • increased immutability of code of the library
  • updated sample apps and documentation

Things to do:

  • bump library version to 0.2.0 (done ➡️ 467c4de)
  • upload Archives to Maven Central Repository
  • close and release artifact on Nexus
  • update gh-pages
  • update CHANGELOG.md after Maven Sync
  • bump library version in README.md after Maven Sync
  • create new GitHub release

Release v. 0.1.1

Initial release notes:

  • bumped RxJava to v. 1.0.14
  • bumped Gradle Build Tools to v. 1.3.1

Release 0.1.2

Initial release notes:

  • now library is emitting OFFLINE status at subscription time, when device is not connected to any network
  • bumped target SDK version to 23
  • bumped buildToolsVersion to 23.0.1
  • removed CHANGE_NETWORK_STATE and INTERNET permissions from AndroidManifest.xml, because they're no longer required

Things to do:

  • bump library version
  • upload archives to Maven Central
  • bump library version to 0.1.2 in README.md after Maven Sync
  • update CHANGELOG.md file after Maven Sync
  • create new GitHub Release

Activity has leaked IntentReceiver

I'm using ReactiveNetwork in a normal Java class and pass an Activity as the Context.
Before the Activity gets destroyed I call mSubscription.unsubscribe, but the error still occurs.
Maybe you can have a look at it?

10-05 23:49:18.350 22518-22518/net.exesystem.carbikeobd.debug E/ActivityThread: Activity has leaked IntentReceiver com.github.pwittchen.reactivenetwork.library.ReactiveNetwork$1$1@380ab58f that was originally registered here. Are you missing a call to unregisterReceiver()?
10-05 23:49:18.350 22518-22518/net.exesystem.carbikeobd.debug E/ActivityThread: android.app.IntentReceiverLeaked: Activity net.exesystem.carbikeobd.activity.Main has leaked IntentReceiver com.github.pwittchen.reactivenetwork.library.ReactiveNetwork$1$1@380ab58f that was originally registered here. Are you missing a call to unregisterReceiver()?
10-05 23:49:18.350 22518-22518/net.exesystem.carbikeobd.debug E/ActivityThread:     at android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:1003)
10-05 23:49:18.350 22518-22518/net.exesystem.carbikeobd.debug E/ActivityThread:     at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:767)
10-05 23:49:18.350 22518-22518/net.exesystem.carbikeobd.debug E/ActivityThread:     at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1749)
10-05 23:49:18.350 22518-22518/net.exesystem.carbikeobd.debug E/ActivityThread:     at android.app.ContextImpl.registerReceiver(ContextImpl.java:1729)
10-05 23:49:18.350 22518-22518/net.exesystem.carbikeobd.debug E/ActivityThread:     at android.app.ContextImpl.registerReceiver(ContextImpl.java:1723)
10-05 23:49:18.350 22518-22518/net.exesystem.carbikeobd.debug E/ActivityThread:     at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:488)
10-05 23:49:18.350 22518-22518/net.exesystem.carbikeobd.debug E/ActivityThread:     at com.github.pwittchen.reactivenetwork.library.ReactiveNetwork$1.call(ReactiveNetwork.java:87)
10-05 23:49:18.350 22518-22518/net.exesystem.carbikeobd.debug E/ActivityThread:     at com.github.pwittchen.reactivenetwork.library.ReactiveNetwork$1.call(ReactiveNetwork.java:70)
10-05 23:49:18.350 22518-22518/net.exesystem.carbikeobd.debug E/ActivityThread:     at rx.Observable$2.call(Observable.java:162)
10-05 23:49:18.350 22518-22518/net.exesystem.carbikeobd.debug E/ActivityThread:     at rx.Observable$2.call(Observable.java:154)
10-05 23:49:18.350 22518-22518/net.exesystem.carbikeobd.debug E/ActivityThread:     at rx.Observable$2.call(Observable.java:162)
10-05 23:49:18.350 22518-22518/net.exesystem.carbikeobd.debug E/ActivityThread:     at rx.Observable$2.call(Observable.java:154)
10-05 23:49:18.350 22518-22518/net.exesystem.carbikeobd.debug E/ActivityThread:     at rx.Observable.unsafeSubscribe(Observable.java:7710)
10-05 23:49:18.350 22518-22518/net.exesystem.carbikeobd.debug E/ActivityThread:     at rx.internal.operators.OperatorSubscribeOn$1$1.call(OperatorSubscribeOn.java:62)
10-05 23:49:18.350 22518-22518/net.exesystem.carbikeobd.debug E/ActivityThread:     at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
10-05 23:49:18.350 22518-22518/net.exesystem.carbikeobd.debug E/ActivityThread:     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
10-05 23:49:18.350 22518-22518/net.exesystem.carbikeobd.debug E/ActivityThread:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
10-05 23:49:18.350 22518-22518/net.exesystem.carbikeobd.debug E/ActivityThread:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
10-05 23:49:18.350 22518-22518/net.exesystem.carbikeobd.debug E/ActivityThread:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
10-05 23:49:18.350 22518-22518/net.exesystem.carbikeobd.debug E/ActivityThread:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
10-05 23:49:18.350 22518-22518/net.exesystem.carbikeobd.debug E/ActivityThread:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
10-05 23:49:18.350 22518-22518/net.exesystem.carbikeobd.debug E/ActivityThread:     at java.lang.Thread.run(Thread.java:818)

Implicit Broadcast Receivers Going Away After Android N

Apparently, Implicit Broadcast Receivers are going away in Android O. 3 of them are already gone in N, which includes the CONNECTIVITY_CHANGE broadcast.

I looked into your code and you don't seem to be using that (rather, you create an instance of a generic broadcast receiver and always call the ConnectivityManager for every broadcast received from it), but it's possible your current method of calling for connectivity changes could still be gone in Android N? Google recommends using the JobScheduler API instead (however, you can only use this starting in API 21...).

I'm thinking that releases should consider using the JobScheduler API instead for listening to connectivity changes (with a shim for using the current broadcast receiver below API 21). What do you think?

Source: https://www.youtube.com/watch?v=VC2Hlb22mZM

XDA has a good TL;DR about this: http://www.xda-developers.com/how-android-n-will-improve-battery-and-memory-management/

Question: nested calling

Hi,

First off amazing library!!!. Thanks for devoting your time 👍
My question might not be specific to your library but I'm stuck in this small problem. I will really appreciate if you can help.

So, basically what i want to achieve is according to the internet connection I want to fire the api call and to do this I think I have to combine 2 observables (one is from your library and one is mine from the api that i'm using).

My attempt:

new ReactiveNetwork().observeConnectivity(context)
.flatMap(new Func1<ConnectivityStatus, Observable<JSONObject>>() {
            // I want to access subscriber in here.
            @Override
            public Observable<JSONObject> call(ConnectivityStatus connectivityStatus) {

                return null;
            }
        })
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
// I want to use onNext, onError 
.subscribe(this);

Not sure if I'm doing this right but will really appreciate if you can help..
Thanks again for devoting your time!!

Make ReactiveNetwork class singleton?

This is a great library. But I have a question about the design of ReactiveNetwork class.
Is there any concerns that does not make ReactiveNetwork class singleton?

Release 0.1.5

Initial release notes:

  • Due to memory leak in WifiManager reported in issue 43945 in Android issue tracker replaced Activity Context with Application Context in sample apps and added appropriate note in README.md
  • added ACCESS_COARSE_LOCATION permission to AndroidManifest.xml to be able to scan WiFi access points on Android 6

Things to do:

  • bump library version to 0.1.5
  • upload Archives to Maven Central Repository
  • close and update artifact on Nexus
  • bump library version in README.md after Maven Sync
  • update CHANGELOG.md after Maven Sync
  • create new GitHub release

observeWifiAccessPoints suddenly doesn't work

my app was being used successfully observeWifiAccessPoints and observeConnectivity and suddenly observeWifiAccessPoints has stopped working (now never goes to "call" procedure).

This is my code:

@Override
protected void onResume() {
    super.onResume();
    // Register interest for two different actions related to power
    registerReceiver(powerMonitor, new IntentFilter("android.intent.action.ACTION_POWER_CONNECTED"));
    registerReceiver(powerMonitor, new IntentFilter("android.intent.action.ACTION_POWER_DISCONNECTED"));


    reactiveNetwork = new ReactiveNetwork();

    reactiveNetwork.observeConnectivity(this)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(new Action1<ConnectivityStatus>() {
                @Override
                public void call(ConnectivityStatus connectivityStatus) {
                    Toast.makeText(MainActivity.this, "connectivityStatus", Toast.LENGTH_SHORT).show();
                    tvConnectivityStatus.setText(connectivityStatus.toString());
                }
            });

    reactiveNetwork.observeWifiAccessPoints(this)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(new Action1<List<ScanResult>>() {
                @Override
                public void call(List<ScanResult> scanResults) {
                    Toast.makeText(MainActivity.this, "observeWifiAccessPoints", Toast.LENGTH_SHORT).show();
                    displayAccessPoints(scanResults);
                }
            });
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.