Listen for Android's CONNECTIVITY_CHANGE broadcasts.
Add the ACCESS_NEWORK_STATE permission to AndroidManifest.xml
<uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE"/>This library exposes three different observables. They all monitor network connectivity the same way, but they provided varying levels of specificity about the state of the network.
Use this observable when all you're interested in is knowing whether the network is connected or not.
ConnectivityManagerconnectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); RxNetwork.connectivityChanges(this, connectivityManager) .subscribe(newAction1<Boolean>(){@Overridepublicvoidcall(Booleanconnected){// [...] } }If you want just a little more information about the state of the network, but don't want to be weighed down by the minutia of things, then use this observable. Read NetworkInfo.State for more information about what you'll get back.
ConnectivityManagerconnectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); RxNetwork.stateChanges(this, connectivityManager) .subscribe(newAction1<NetworkInfo.State>(){@Overridepublicvoidcall(NetworkInfo.Statestate){// [...] } }Here's the big daddy. This observable will tell you the "fine-grained" state of the network. Read NetworkInfo.DetailedState for more information about what you'll get back.
ConnectivityManagerconnectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); RxNetwork.connectivityChanges(this, connectivityManager) .subscribe(newAction1<NetworkInfo.DetailedState>(){@Overridepublicvoidcall(NetworkInfo.DetailedStatedetailedState){// [...] } }Add the JitPack repository to your root build.gradle at the end of repositories:
allprojects{repositories{... maven{url "https://jitpack.io" } } }And then add this library to your project:
dependencies{compile 'io.andref:Rx.Network:1.0.1' }Copyright 2016 Michael De Soto
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.