├── example
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ ├── drawable-hdpi
│ │ │ └── ic_launcher.png
│ │ ├── drawable-mdpi
│ │ │ └── ic_launcher.png
│ │ ├── drawable-xhdpi
│ │ │ └── ic_launcher.png
│ │ ├── drawable-xxhdpi
│ │ │ └── ic_launcher.png
│ │ ├── values
│ │ │ ├── styles.xml
│ │ │ ├── dimens.xml
│ │ │ └── strings.xml
│ │ ├── values-w820dp
│ │ │ └── dimens.xml
│ │ └── layout
│ │ │ └── activity_main.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── com
│ │ └── github
│ │ └── pwittchen
│ │ └── networkevents
│ │ └── app
│ │ └── MainActivity.java
├── proguard-rules.pro
└── build.gradle
├── example-greenrobot-bus
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ ├── mipmap-hdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-xxhdpi
│ │ │ └── ic_launcher.png
│ │ ├── values
│ │ │ ├── dimens.xml
│ │ │ ├── styles.xml
│ │ │ └── strings.xml
│ │ ├── values-w820dp
│ │ │ └── dimens.xml
│ │ └── layout
│ │ │ └── activity_main.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── com
│ │ └── github
│ │ └── pwittchen
│ │ └── networkevents
│ │ └── greenrobot
│ │ └── app
│ │ └── MainActivity.java
├── proguard-rules.pro
└── build.gradle
├── network-events-library
├── .gitignore
├── gradle.properties
├── src
│ ├── main
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── com
│ │ │ └── github
│ │ │ └── pwittchen
│ │ │ └── networkevents
│ │ │ └── library
│ │ │ ├── logger
│ │ │ ├── Logger.java
│ │ │ └── NetworkEventsLogger.java
│ │ │ ├── NetworkState.java
│ │ │ ├── BusWrapper.java
│ │ │ ├── internet
│ │ │ ├── OnlineChecker.java
│ │ │ └── OnlineCheckerImpl.java
│ │ │ ├── MobileNetworkType.java
│ │ │ ├── ConnectivityStatus.java
│ │ │ ├── event
│ │ │ ├── WifiSignalStrengthChanged.java
│ │ │ └── ConnectivityChanged.java
│ │ │ ├── NetworkHelper.java
│ │ │ ├── receiver
│ │ │ ├── WifiSignalStrengthChangeReceiver.java
│ │ │ ├── BaseBroadcastReceiver.java
│ │ │ ├── NetworkConnectionChangeReceiver.java
│ │ │ └── InternetConnectionChangeReceiver.java
│ │ │ └── NetworkEvents.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── github
│ │ └── pwittchen
│ │ └── networkevents
│ │ └── library
│ │ ├── utils
│ │ ├── OttoBusWrapper.java
│ │ └── TestUtils.java
│ │ ├── NetworkEventsTest.java
│ │ └── receiver
│ │ ├── WifiSignalStrengthChangeReceiverTest.java
│ │ ├── InternetConnectionChangeReceiverTest.java
│ │ └── NetworkConnectionChangeReceiverTest.java
├── proguard-rules.pro
└── build.gradle
├── .gitignore
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradle.properties
├── .travis.yml
├── gradlew.bat
├── maven_push.gradle
├── gradlew
├── CHANGELOG.md
├── LICENSE
└── README.md
/example/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/example-greenrobot-bus/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/network-events-library/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /.gradle
2 | /local.properties
3 | /.idea
4 | /.DS_Store
5 | /build
6 | *.iml
7 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':example', ':network-events-library', ':example-greenrobot-bus'
2 |
--------------------------------------------------------------------------------
/network-events-library/gradle.properties:
--------------------------------------------------------------------------------
1 | POM_NAME=networkevents
2 | POM_ARTIFACT_ID=networkevents
3 | POM_PACKAGING=aar
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pwittchen/NetworkEvents/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/example/src/main/res/drawable-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pwittchen/NetworkEvents/HEAD/example/src/main/res/drawable-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/src/main/res/drawable-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pwittchen/NetworkEvents/HEAD/example/src/main/res/drawable-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/src/main/res/drawable-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pwittchen/NetworkEvents/HEAD/example/src/main/res/drawable-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/src/main/res/drawable-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pwittchen/NetworkEvents/HEAD/example/src/main/res/drawable-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
--------------------------------------------------------------------------------
/example-greenrobot-bus/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pwittchen/NetworkEvents/HEAD/example-greenrobot-bus/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example-greenrobot-bus/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pwittchen/NetworkEvents/HEAD/example-greenrobot-bus/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example-greenrobot-bus/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pwittchen/NetworkEvents/HEAD/example-greenrobot-bus/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example-greenrobot-bus/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pwittchen/NetworkEvents/HEAD/example-greenrobot-bus/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 | 16dp
3 | 16dp
4 | 10dp
5 |
6 |
--------------------------------------------------------------------------------
/example-greenrobot-bus/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 | 16dp
3 | 16dp
4 | 10dp
5 |
6 |
--------------------------------------------------------------------------------
/example-greenrobot-bus/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sat Jun 25 22:20:52 CEST 2016
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip
7 |
--------------------------------------------------------------------------------
/example/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/example-greenrobot-bus/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/network-events-library/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | VERSION_NAME=2.1.6
2 | VERSION_CODE=15
3 | GROUP=com.github.pwittchen
4 |
5 | POM_DESCRIPTION=Android library listening network connection state and change of the Wifi signal strength
6 | POM_URL=https://github.com/pwittchen/NetworkEvents
7 | POM_SCM_URL=https://github.com/pwittchen/NetworkEvents
8 | POM_SCM_CONNECTION=scm:git@github.com:pwittchen/NetworkEvents.git
9 | POM_SCM_DEV_CONNECTION=scm:git@github.com:pwittchen/NetworkEvents.git
10 | POM_LICENCE_NAME=The Apache Software License, Version 2.0
11 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt
12 | POM_LICENCE_DIST=repo
13 | POM_DEVELOPER_ID=pwittchen
14 | POM_DEVELOPER_NAME=Piotr Wittchen
15 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: android
2 |
3 | android:
4 | components:
5 | - build-tools-23.0.1
6 | - android-23
7 | - extra-android-m2repository
8 | - extra-google-m2repository
9 |
10 | install:
11 | # Check install section: http://docs.travis-ci.com/user/build-configuration/#install
12 | # If you'd like to skip the install stage entirely, set it to true and nothing will be run.
13 | - true
14 |
15 | sudo: false
16 |
17 | script:
18 | # By default Travis-ci executes './gradlew build connectedCheck' if no 'script:' section found.
19 | # We are skipping Unit Tests, because Travis is not able to start emulator required for them (it's still in exmperimental phase)
20 | - ./gradlew clean build
21 |
--------------------------------------------------------------------------------
/example/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in C:\android-sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/example/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/network-events-library/src/androidTest/java/com/github/pwittchen/networkevents/library/utils/OttoBusWrapper.java:
--------------------------------------------------------------------------------
1 | package com.github.pwittchen.networkevents.library.utils;
2 |
3 | import com.github.pwittchen.networkevents.library.BusWrapper;
4 | import com.squareup.otto.Bus;
5 |
6 | public final class OttoBusWrapper implements BusWrapper {
7 | private Bus bus;
8 |
9 | public OttoBusWrapper(Bus bus) {
10 | this.bus = bus;
11 | }
12 |
13 | @Override public void register(Object object) {
14 | bus.register(object);
15 | }
16 |
17 | @Override public void unregister(Object object) {
18 | bus.unregister(object);
19 | }
20 |
21 | @Override public void post(Object event) {
22 | bus.post(event);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/network-events-library/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in C:/android-sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/example-greenrobot-bus/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /home/piotr/Android/Sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/example/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion "23.0.1"
6 |
7 | defaultConfig {
8 | applicationId "com.github.pwittchen.networkevents.app"
9 | minSdkVersion 15
10 | targetSdkVersion 23
11 | versionCode 1
12 | versionName "1.0"
13 | }
14 |
15 | buildTypes {
16 | release {
17 | minifyEnabled false
18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
19 | }
20 | }
21 |
22 | lintOptions {
23 | abortOnError false
24 | }
25 | }
26 |
27 | dependencies {
28 | compile project(':network-events-library')
29 | compile 'com.squareup:otto:1.3.8'
30 | compile 'com.android.support:appcompat-v7:23.0.0'
31 | }
32 |
--------------------------------------------------------------------------------
/example/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | NetworkEvents example
4 | Waiting for connectivity status…
5 | Wifi signal strength changed
6 | Connectivity status:
7 | Mobile network type:
8 | Available Access Points:
9 | WiFi signal strength change counter:
10 | Waiting for signal strength change…
11 |
12 |
--------------------------------------------------------------------------------
/example-greenrobot-bus/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
12 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/example-greenrobot-bus/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | NetworkEvents example
4 | Waiting for connectivity status…
5 | Wifi signal strength changed
6 | Connectivity status:
7 | Mobile network type:
8 | Available Access Points:
9 | WiFi signal strength change counter:
10 | Waiting for signal strength change…
11 |
12 |
--------------------------------------------------------------------------------
/example-greenrobot-bus/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion "23.0.1"
6 |
7 | defaultConfig {
8 | applicationId "com.github.pwittchen.networkevents.greenrobot.app"
9 | minSdkVersion 15
10 | targetSdkVersion 23
11 | versionCode 1
12 | versionName "1.0"
13 | }
14 |
15 | buildTypes {
16 | release {
17 | minifyEnabled false
18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
19 | }
20 | }
21 |
22 | lintOptions {
23 | abortOnError false
24 | }
25 | }
26 |
27 | dependencies {
28 | compile(project(':network-events-library'))
29 |
30 | // Greenrobot EventBus 3 Beta
31 | compile 'org.greenrobot:eventbus:3.0.0'
32 | compile 'com.android.support:appcompat-v7:23.0.0'
33 | }
34 |
--------------------------------------------------------------------------------
/network-events-library/src/main/java/com/github/pwittchen/networkevents/library/logger/Logger.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Piotr Wittchen
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.pwittchen.networkevents.library.logger;
17 |
18 | public interface Logger {
19 | void log(String message);
20 | }
21 |
--------------------------------------------------------------------------------
/network-events-library/src/main/java/com/github/pwittchen/networkevents/library/NetworkState.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Piotr Wittchen
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.pwittchen.networkevents.library;
17 |
18 | public final class NetworkState {
19 | public static ConnectivityStatus status = ConnectivityStatus.UNKNOWN;
20 | }
21 |
--------------------------------------------------------------------------------
/network-events-library/src/main/java/com/github/pwittchen/networkevents/library/BusWrapper.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Piotr Wittchen
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.pwittchen.networkevents.library;
17 |
18 | public interface BusWrapper {
19 | void register(Object object);
20 |
21 | void unregister(Object object);
22 |
23 | void post(Object event);
24 | }
25 |
--------------------------------------------------------------------------------
/network-events-library/src/main/java/com/github/pwittchen/networkevents/library/internet/OnlineChecker.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Piotr Wittchen
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.pwittchen.networkevents.library.internet;
17 |
18 | public interface OnlineChecker {
19 | void check();
20 |
21 | void setPingParameters(String host, int port, int timeoutInMs);
22 | }
23 |
--------------------------------------------------------------------------------
/network-events-library/src/main/java/com/github/pwittchen/networkevents/library/logger/NetworkEventsLogger.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Piotr Wittchen
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.pwittchen.networkevents.library.logger;
17 |
18 | import android.util.Log;
19 |
20 | /**
21 | * Logs events to LogCat
22 | */
23 | public final class NetworkEventsLogger implements Logger {
24 | private final static String TAG = "NetworkEvents";
25 |
26 | @Override public void log(String message) {
27 | Log.d(TAG, message);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/network-events-library/src/main/java/com/github/pwittchen/networkevents/library/MobileNetworkType.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Piotr Wittchen
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.pwittchen.networkevents.library;
17 |
18 | public enum MobileNetworkType {
19 | UNKNOWN("unknown"),
20 | LTE("LTE"),
21 | HSPAP("HSPAP"),
22 | EDGE("EDGE"),
23 | GPRS("GPRS");
24 |
25 | private final String type;
26 |
27 | MobileNetworkType(String status) {
28 | this.type = status;
29 | }
30 |
31 | @Override public String toString() {
32 | return type;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/network-events-library/src/androidTest/java/com/github/pwittchen/networkevents/library/utils/TestUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Piotr Wittchen
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.pwittchen.networkevents.library.utils;
17 |
18 | import com.github.pwittchen.networkevents.library.event.ConnectivityChanged;
19 | import com.squareup.otto.Subscribe;
20 |
21 | import java.util.List;
22 |
23 | public final class TestUtils {
24 | public static Object getConnectivityEventCatcher(final List events) {
25 | return new Object() {
26 | @SuppressWarnings("unused") @Subscribe
27 | public void onConnectivityChanged(ConnectivityChanged event) {
28 | events.add(event);
29 | }
30 | };
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/network-events-library/src/main/java/com/github/pwittchen/networkevents/library/ConnectivityStatus.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Piotr Wittchen
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.pwittchen.networkevents.library;
17 |
18 | public enum ConnectivityStatus {
19 | UNKNOWN("unknown"),
20 | WIFI_CONNECTED("connected to WiFi"),
21 | WIFI_CONNECTED_HAS_INTERNET("connected to WiFi (Internet available)"),
22 | WIFI_CONNECTED_HAS_NO_INTERNET("connected to WiFi (Internet not available)"),
23 | MOBILE_CONNECTED("connected to mobile network"),
24 | OFFLINE("offline");
25 |
26 | private final String status;
27 |
28 | ConnectivityStatus(String status) {
29 | this.status = status;
30 | }
31 |
32 | @Override public String toString() {
33 | return status;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/network-events-library/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion "23.0.1"
6 |
7 | defaultConfig {
8 | minSdkVersion 9
9 | targetSdkVersion 23
10 | versionCode 1
11 | versionName "1.0"
12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
13 | }
14 |
15 | buildTypes {
16 | debug {
17 | testCoverageEnabled = true
18 | }
19 |
20 | release {
21 | minifyEnabled false
22 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
23 | }
24 | }
25 |
26 | packagingOptions {
27 | exclude 'LICENSE.txt'
28 | exclude 'META-INF/LICENSE.txt'
29 | }
30 |
31 | lintOptions {
32 | abortOnError false
33 | }
34 | }
35 |
36 | dependencies {
37 | androidTestCompile 'com.squareup:otto:1.3.8' // Otto event bus is used only in unit tests now
38 | androidTestCompile 'com.android.support.test:testing-support-lib:0.1'
39 | androidTestCompile('com.google.truth:truth:0.28') {
40 | exclude group: 'junit' // Android has JUnit built in
41 | }
42 | androidTestCompile 'com.google.dexmaker:dexmaker:1.0' // required by Mockito
43 | androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.0' // required by Mockito
44 | androidTestCompile 'org.mockito:mockito-core:1.10.19'
45 | }
46 |
47 | task wrapper(type: Wrapper) {
48 | gradleVersion = '2.2.1'
49 | }
50 |
51 | apply from: '../maven_push.gradle'
52 |
--------------------------------------------------------------------------------
/network-events-library/src/androidTest/java/com/github/pwittchen/networkevents/library/NetworkEventsTest.java:
--------------------------------------------------------------------------------
1 | package com.github.pwittchen.networkevents.library;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import com.github.pwittchen.networkevents.library.utils.OttoBusWrapper;
8 | import com.squareup.otto.Bus;
9 |
10 | import org.junit.Test;
11 | import org.junit.runner.RunWith;
12 |
13 | @RunWith(AndroidJUnit4.class) public class NetworkEventsTest {
14 |
15 | @Test(expected = IllegalArgumentException.class) public void testContextShouldNotBeNull() {
16 | // given
17 | Context nullContext = null;
18 | BusWrapper busWrapper = new OttoBusWrapper(new Bus());
19 |
20 | // when
21 | new NetworkEvents(nullContext, busWrapper);
22 |
23 | // then throw an exception
24 | }
25 |
26 | @Test(expected = IllegalArgumentException.class) public void testBusShouldNotBeNull() {
27 | // given
28 | Context context = InstrumentationRegistry.getContext();
29 | BusWrapper nullBusWrapper = null;
30 |
31 | // when
32 | new NetworkEvents(context, nullBusWrapper);
33 |
34 | // then throw an exception
35 | }
36 |
37 | @Test(expected = IllegalArgumentException.class)
38 | public void testShouldNotRegisterWhenContextAndBusAreNull() {
39 | // given
40 | NetworkEvents networkEvents = new NetworkEvents(null, null);
41 |
42 | // when
43 | networkEvents.register();
44 |
45 | // then throw an exception
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/network-events-library/src/main/java/com/github/pwittchen/networkevents/library/event/WifiSignalStrengthChanged.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Piotr Wittchen
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.pwittchen.networkevents.library.event;
17 |
18 | import android.content.Context;
19 | import android.net.wifi.ScanResult;
20 | import android.net.wifi.WifiManager;
21 |
22 | import com.github.pwittchen.networkevents.library.logger.Logger;
23 |
24 | import java.util.List;
25 |
26 | /**
27 | * Event pushed to Otto Event Bus when Wifi Signal strength was changed
28 | * and list of WiFi Access Points was refreshed
29 | */
30 | public final class WifiSignalStrengthChanged {
31 | private static final String MESSAGE = "WifiSignalStrengthChanged";
32 | private Context context;
33 |
34 | public WifiSignalStrengthChanged(Logger logger, Context context) {
35 | this.context = context;
36 | logger.log(MESSAGE);
37 | }
38 |
39 | public List getWifiScanResults() {
40 | WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
41 | return wifiManager.getScanResults();
42 | }
43 | }
--------------------------------------------------------------------------------
/network-events-library/src/main/java/com/github/pwittchen/networkevents/library/NetworkHelper.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Piotr Wittchen
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.pwittchen.networkevents.library;
17 |
18 | import android.content.Context;
19 | import android.net.ConnectivityManager;
20 | import android.net.NetworkInfo;
21 |
22 | public final class NetworkHelper {
23 |
24 | private NetworkHelper() {
25 | }
26 |
27 | /**
28 | * Helper method, which checks if device is connected to WiFi or mobile network.
29 | *
30 | * @param context Activity or application context
31 | * @return boolean true if is connected to mobile or WiFi network.
32 | */
33 | public static boolean isConnectedToWiFiOrMobileNetwork(Context context) {
34 | final String service = Context.CONNECTIVITY_SERVICE;
35 | final ConnectivityManager manager = (ConnectivityManager) context.getSystemService(service);
36 | final NetworkInfo networkInfo = manager.getActiveNetworkInfo();
37 |
38 | if (networkInfo == null) {
39 | return false;
40 | }
41 |
42 | final boolean isWifiNetwork = networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
43 | final boolean isMobileNetwork = networkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
44 |
45 | if (isWifiNetwork || isMobileNetwork) {
46 | return true;
47 | }
48 |
49 | return false;
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/network-events-library/src/main/java/com/github/pwittchen/networkevents/library/receiver/WifiSignalStrengthChangeReceiver.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Piotr Wittchen
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.pwittchen.networkevents.library.receiver;
17 |
18 | import android.content.Context;
19 | import android.content.Intent;
20 | import android.net.wifi.WifiManager;
21 |
22 | import com.github.pwittchen.networkevents.library.BusWrapper;
23 | import com.github.pwittchen.networkevents.library.event.WifiSignalStrengthChanged;
24 | import com.github.pwittchen.networkevents.library.logger.Logger;
25 |
26 | public final class WifiSignalStrengthChangeReceiver extends BaseBroadcastReceiver {
27 | private Context context;
28 |
29 | public WifiSignalStrengthChangeReceiver(BusWrapper busWrapper, Logger logger, Context context) {
30 | super(busWrapper, logger, context);
31 | this.context = context;
32 | }
33 |
34 | @Override public void onReceive(Context context, Intent intent) {
35 | // We need to start WiFi scan after receiving an Intent
36 | // in order to get update with fresh data as soon as possible
37 | WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
38 | wifiManager.startScan();
39 | onPostReceive();
40 | }
41 |
42 | public void onPostReceive() {
43 | postFromAnyThread(new WifiSignalStrengthChanged(logger, context));
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/network-events-library/src/main/java/com/github/pwittchen/networkevents/library/receiver/BaseBroadcastReceiver.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Piotr Wittchen
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.pwittchen.networkevents.library.receiver;
17 |
18 | import android.content.BroadcastReceiver;
19 | import android.content.Context;
20 | import android.content.Intent;
21 | import android.os.Handler;
22 | import android.os.Looper;
23 |
24 | import com.github.pwittchen.networkevents.library.BusWrapper;
25 | import com.github.pwittchen.networkevents.library.ConnectivityStatus;
26 | import com.github.pwittchen.networkevents.library.NetworkState;
27 | import com.github.pwittchen.networkevents.library.event.ConnectivityChanged;
28 | import com.github.pwittchen.networkevents.library.logger.Logger;
29 |
30 | public abstract class BaseBroadcastReceiver extends BroadcastReceiver {
31 | private final Handler handler = new Handler(Looper.getMainLooper());
32 | private final BusWrapper busWrapper;
33 | private final Context context;
34 | protected final Logger logger;
35 |
36 | public BaseBroadcastReceiver(BusWrapper busWrapper, Logger logger, Context context) {
37 | this.busWrapper = busWrapper;
38 | this.logger = logger;
39 | this.context = context;
40 | }
41 |
42 | @Override public abstract void onReceive(Context context, Intent intent);
43 |
44 | protected boolean statusNotChanged(ConnectivityStatus connectivityStatus) {
45 | return NetworkState.status == connectivityStatus;
46 | }
47 |
48 | protected void postConnectivityChanged(ConnectivityStatus connectivityStatus) {
49 | NetworkState.status = connectivityStatus;
50 | postFromAnyThread(new ConnectivityChanged(connectivityStatus, logger, context));
51 | }
52 |
53 | protected void postFromAnyThread(final Object event) {
54 | if (Looper.myLooper() == Looper.getMainLooper()) {
55 | busWrapper.post(event);
56 | } else {
57 | handler.post(new Runnable() {
58 | @Override public void run() {
59 | busWrapper.post(event);
60 | }
61 | });
62 | }
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/network-events-library/src/main/java/com/github/pwittchen/networkevents/library/internet/OnlineCheckerImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Piotr Wittchen
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.pwittchen.networkevents.library.internet;
17 |
18 | import android.content.Context;
19 | import android.content.Intent;
20 | import android.os.AsyncTask;
21 | import com.github.pwittchen.networkevents.library.receiver.InternetConnectionChangeReceiver;
22 | import java.io.IOException;
23 | import java.net.InetSocketAddress;
24 | import java.net.Socket;
25 |
26 | public final class OnlineCheckerImpl implements OnlineChecker {
27 | private static final String DEFAULT_PING_HOST = "www.google.com";
28 | private static final int DEFAULT_PING_PORT = 80;
29 | private static final int DEFAULT_PING_TIMEOUT_IN_MS = 2000;
30 |
31 | private final Context context;
32 | private String pingHost;
33 | private int pingPort;
34 | private int pingTimeout;
35 |
36 | public OnlineCheckerImpl(Context context) {
37 | this.context = context;
38 | this.pingHost = DEFAULT_PING_HOST;
39 | this.pingPort = DEFAULT_PING_PORT;
40 | this.pingTimeout = DEFAULT_PING_TIMEOUT_IN_MS;
41 | }
42 |
43 | @Override public void check() {
44 | new AsyncTask() {
45 | @Override protected Void doInBackground(Void... params) {
46 | boolean isOnline = false;
47 | try {
48 | Socket socket = new Socket();
49 | socket.connect(new InetSocketAddress(pingHost, pingPort), pingTimeout);
50 | isOnline = socket.isConnected();
51 | } catch (IOException e) {
52 | isOnline = false;
53 | } finally {
54 | sendBroadcast(isOnline);
55 | }
56 | return null;
57 | }
58 | }.execute();
59 | }
60 |
61 | @Override public void setPingParameters(String host, int port, int timeoutInMs) {
62 | this.pingHost = host;
63 | this.pingPort = port;
64 | this.pingTimeout = timeoutInMs;
65 | }
66 |
67 | private void sendBroadcast(boolean isOnline) {
68 | Intent intent = new Intent(InternetConnectionChangeReceiver.INTENT);
69 | intent.putExtra(InternetConnectionChangeReceiver.INTENT_EXTRA, isOnline);
70 | context.sendBroadcast(intent);
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/network-events-library/src/main/java/com/github/pwittchen/networkevents/library/event/ConnectivityChanged.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Piotr Wittchen
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.pwittchen.networkevents.library.event;
17 |
18 | import android.content.Context;
19 | import android.telephony.TelephonyManager;
20 |
21 | import com.github.pwittchen.networkevents.library.ConnectivityStatus;
22 | import com.github.pwittchen.networkevents.library.MobileNetworkType;
23 | import com.github.pwittchen.networkevents.library.logger.Logger;
24 |
25 | /**
26 | * Event pushed to Otto Event Bus when ConnectivityStatus changes;
27 | * E.g. when WiFi is turned on or off or when mobile network is turned on or off
28 | * it also occurs when WiFi is on, but there is no Internet connection or when there is Internet
29 | * connection
30 | * or when device goes off-line
31 | */
32 | public final class ConnectivityChanged {
33 | private static final String MESSAGE_FORMAT = "ConnectivityChanged: %s";
34 | private final ConnectivityStatus connectivityStatus;
35 | private final Context context;
36 |
37 | public ConnectivityChanged(ConnectivityStatus connectivityStatus, Logger logger,
38 | Context context) {
39 | this.connectivityStatus = connectivityStatus;
40 | this.context = context;
41 | String message = String.format(MESSAGE_FORMAT, connectivityStatus.toString());
42 | logger.log(message);
43 | }
44 |
45 | public ConnectivityStatus getConnectivityStatus() {
46 | return connectivityStatus;
47 | }
48 |
49 | public MobileNetworkType getMobileNetworkType() {
50 |
51 | if (connectivityStatus != ConnectivityStatus.MOBILE_CONNECTED) {
52 | return MobileNetworkType.UNKNOWN;
53 | }
54 |
55 | TelephonyManager telephonyManager =
56 | (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
57 |
58 | switch (telephonyManager.getNetworkType()) {
59 | case (TelephonyManager.NETWORK_TYPE_LTE):
60 | return MobileNetworkType.LTE;
61 | case (TelephonyManager.NETWORK_TYPE_HSPAP):
62 | return MobileNetworkType.HSPAP;
63 | case (TelephonyManager.NETWORK_TYPE_EDGE):
64 | return MobileNetworkType.EDGE;
65 | case (TelephonyManager.NETWORK_TYPE_GPRS):
66 | return MobileNetworkType.GPRS;
67 | default:
68 | return MobileNetworkType.UNKNOWN;
69 | }
70 | }
71 | }
--------------------------------------------------------------------------------
/network-events-library/src/androidTest/java/com/github/pwittchen/networkevents/library/receiver/WifiSignalStrengthChangeReceiverTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Piotr Wittchen
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.pwittchen.networkevents.library.receiver;
17 |
18 | import android.content.Context;
19 | import android.support.test.runner.AndroidJUnit4;
20 |
21 | import com.github.pwittchen.networkevents.library.BusWrapper;
22 | import com.github.pwittchen.networkevents.library.logger.Logger;
23 | import com.github.pwittchen.networkevents.library.event.WifiSignalStrengthChanged;
24 | import com.github.pwittchen.networkevents.library.utils.OttoBusWrapper;
25 | import com.squareup.otto.Bus;
26 | import com.squareup.otto.Subscribe;
27 | import com.squareup.otto.ThreadEnforcer;
28 |
29 | import org.junit.Before;
30 | import org.junit.Test;
31 | import org.junit.runner.RunWith;
32 | import org.mockito.Mockito;
33 |
34 | import java.util.ArrayList;
35 | import java.util.List;
36 |
37 | import static com.google.common.truth.Truth.assertThat;
38 |
39 | @RunWith(AndroidJUnit4.class) public class WifiSignalStrengthChangeReceiverTest {
40 |
41 | private WifiSignalStrengthChangeReceiver receiver;
42 | private BusWrapper busWrapper;
43 |
44 | @Before public void setUp() throws Exception {
45 | this.busWrapper = new OttoBusWrapper(new Bus(ThreadEnforcer.ANY));
46 | Logger logger = Mockito.mock(Logger.class);
47 | Context context = Mockito.mock(Context.class);
48 | this.receiver = new WifiSignalStrengthChangeReceiver(busWrapper, logger, context);
49 | }
50 |
51 | @Test public void testShouldReceiveAnEventWhenWifiSignalStrengthChanged()
52 | throws InterruptedException {
53 | // given
54 | final List connectivityChangeEvents = new ArrayList<>();
55 | Object eventCatcher = getWifiEventCatcher(connectivityChangeEvents);
56 | busWrapper.register(eventCatcher);
57 |
58 | // when
59 | receiver.onPostReceive();
60 | Thread.sleep(2000); // wait a while for async operation
61 |
62 | // then
63 | assertThat(connectivityChangeEvents).isNotEmpty();
64 | busWrapper.unregister(eventCatcher);
65 | }
66 |
67 | private static Object getWifiEventCatcher(final List events) {
68 | return new Object() {
69 | @SuppressWarnings("unused") @Subscribe
70 | public void onWifiSignalStrengthChanged(WifiSignalStrengthChanged event) {
71 | events.add(event);
72 | }
73 | };
74 | }
75 | }
--------------------------------------------------------------------------------
/network-events-library/src/main/java/com/github/pwittchen/networkevents/library/receiver/NetworkConnectionChangeReceiver.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Piotr Wittchen
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.pwittchen.networkevents.library.receiver;
17 |
18 | import android.content.Context;
19 | import android.content.Intent;
20 | import android.net.ConnectivityManager;
21 | import android.net.NetworkInfo;
22 |
23 | import com.github.pwittchen.networkevents.library.BusWrapper;
24 | import com.github.pwittchen.networkevents.library.ConnectivityStatus;
25 | import com.github.pwittchen.networkevents.library.internet.OnlineChecker;
26 | import com.github.pwittchen.networkevents.library.logger.Logger;
27 |
28 | public final class NetworkConnectionChangeReceiver extends BaseBroadcastReceiver {
29 | private final OnlineChecker onlineChecker;
30 | private boolean internetCheckEnabled = false;
31 |
32 | public NetworkConnectionChangeReceiver(BusWrapper busWrapper, Logger logger, Context context,
33 | OnlineChecker onlineChecker) {
34 | super(busWrapper, logger, context);
35 | this.onlineChecker = onlineChecker;
36 | }
37 |
38 | public void enableInternetCheck() {
39 | this.internetCheckEnabled = true;
40 | }
41 |
42 | @Override public void onReceive(final Context context, Intent intent) {
43 | onPostReceive(getConnectivityStatus(context));
44 | }
45 |
46 | public void onPostReceive(final ConnectivityStatus connectivityStatus) {
47 | if (statusNotChanged(connectivityStatus)) {
48 | return;
49 | }
50 |
51 | boolean isConnectedToWifi = connectivityStatus == ConnectivityStatus.WIFI_CONNECTED;
52 |
53 | if (internetCheckEnabled && isConnectedToWifi) {
54 | onlineChecker.check();
55 | } else {
56 | postConnectivityChanged(connectivityStatus);
57 | }
58 | }
59 |
60 | private ConnectivityStatus getConnectivityStatus(Context context) {
61 | ConnectivityManager connectivityManager =
62 | (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
63 | NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
64 |
65 | if (networkInfo != null) {
66 | if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
67 | return ConnectivityStatus.WIFI_CONNECTED;
68 | } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
69 | return ConnectivityStatus.MOBILE_CONNECTED;
70 | }
71 | }
72 |
73 | return ConnectivityStatus.OFFLINE;
74 | }
75 | }
--------------------------------------------------------------------------------
/network-events-library/src/main/java/com/github/pwittchen/networkevents/library/receiver/InternetConnectionChangeReceiver.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Piotr Wittchen
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.pwittchen.networkevents.library.receiver;
17 |
18 | import android.content.Context;
19 | import android.content.Intent;
20 | import android.net.ConnectivityManager;
21 | import android.net.NetworkInfo;
22 |
23 | import com.github.pwittchen.networkevents.library.BusWrapper;
24 | import com.github.pwittchen.networkevents.library.ConnectivityStatus;
25 | import com.github.pwittchen.networkevents.library.logger.Logger;
26 |
27 | public final class InternetConnectionChangeReceiver extends BaseBroadcastReceiver {
28 | public final static String INTENT =
29 | "networkevents.intent.action.INTERNET_CONNECTION_STATE_CHANGED";
30 | public final static String INTENT_EXTRA = "networkevents.intent.extra.CONNECTED_TO_INTERNET";
31 |
32 | public InternetConnectionChangeReceiver(BusWrapper busWrapper, Logger logger, Context context) {
33 | super(busWrapper, logger, context);
34 | }
35 |
36 | @Override public void onReceive(Context context, Intent intent) {
37 | if (intent.getAction().equals(INTENT)) {
38 | boolean connectedToInternet = intent.getBooleanExtra(INTENT_EXTRA, false);
39 | onPostReceive(connectedToInternet, context);
40 | }
41 | }
42 |
43 | public void onPostReceive(boolean connectedToInternet, Context context) {
44 | ConnectivityStatus connectivityStatus =
45 | (connectedToInternet) ? ConnectivityStatus.WIFI_CONNECTED_HAS_INTERNET
46 | : ConnectivityStatus.WIFI_CONNECTED_HAS_NO_INTERNET;
47 |
48 | if (statusNotChanged(connectivityStatus)) {
49 | return;
50 | }
51 |
52 | // we are checking if device is connected to WiFi again,
53 | // because connectivityStatus may change in a short period of time
54 | // after receiving it
55 |
56 | if (context != null && !isConnectedToWifi(context)) {
57 | return;
58 | }
59 |
60 | postConnectivityChanged(connectivityStatus);
61 | }
62 |
63 | private boolean isConnectedToWifi(Context context) {
64 | ConnectivityManager connectivityManager =
65 | (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
66 | NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
67 |
68 | if (networkInfo != null) {
69 | return networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
70 | }
71 |
72 | return false;
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/example/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
9 |
10 |
19 |
20 |
29 |
30 |
40 |
41 |
50 |
51 |
61 |
62 |
67 |
68 |
69 |
--------------------------------------------------------------------------------
/example-greenrobot-bus/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
9 |
10 |
19 |
20 |
29 |
30 |
40 |
41 |
50 |
51 |
61 |
62 |
67 |
68 |
69 |
--------------------------------------------------------------------------------
/maven_push.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013 Chris Banes
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | apply plugin: 'maven'
18 | apply plugin: 'signing'
19 |
20 | def isReleaseBuild() {
21 | return VERSION_NAME.contains("SNAPSHOT") == false
22 | }
23 |
24 | def getReleaseRepositoryUrl() {
25 | return hasProperty('RELEASE_REPOSITORY_URL') ? RELEASE_REPOSITORY_URL :
26 | "https://oss.sonatype.org/service/local/staging/deploy/maven2/"
27 | }
28 |
29 | def getSnapshotRepositoryUrl() {
30 | return hasProperty('SNAPSHOT_REPOSITORY_URL') ? SNAPSHOT_REPOSITORY_URL :
31 | "https://oss.sonatype.org/content/repositories/snapshots/"
32 | }
33 |
34 | def getRepositoryUsername() {
35 | return hasProperty('NEXUS_USERNAME') ? NEXUS_USERNAME : ""
36 | }
37 |
38 | def getRepositoryPassword() {
39 | return hasProperty('NEXUS_PASSWORD') ? NEXUS_PASSWORD : ""
40 | }
41 |
42 | afterEvaluate { project ->
43 | uploadArchives {
44 | repositories {
45 | mavenDeployer {
46 | beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
47 |
48 | pom.groupId = GROUP
49 | pom.artifactId = POM_ARTIFACT_ID
50 | pom.version = VERSION_NAME
51 |
52 | repository(url: getReleaseRepositoryUrl()) {
53 | authentication(userName: getRepositoryUsername(), password: getRepositoryPassword())
54 | }
55 | snapshotRepository(url: getSnapshotRepositoryUrl()) {
56 | authentication(userName: getRepositoryUsername(), password: getRepositoryPassword())
57 | }
58 |
59 | pom.project {
60 | name POM_NAME
61 | packaging POM_PACKAGING
62 | description POM_DESCRIPTION
63 | url POM_URL
64 |
65 | scm {
66 | url POM_SCM_URL
67 | connection POM_SCM_CONNECTION
68 | developerConnection POM_SCM_DEV_CONNECTION
69 | }
70 |
71 | licenses {
72 | license {
73 | name POM_LICENCE_NAME
74 | url POM_LICENCE_URL
75 | distribution POM_LICENCE_DIST
76 | }
77 | }
78 |
79 | developers {
80 | developer {
81 | id POM_DEVELOPER_ID
82 | name POM_DEVELOPER_NAME
83 | }
84 | }
85 | }
86 | }
87 | }
88 | }
89 |
90 | signing {
91 | required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") }
92 | sign configurations.archives
93 | }
94 |
95 | task androidJavadocs(type: Javadoc) {
96 | source = android.sourceSets.main.java.srcDirs
97 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
98 | failOnError = false
99 | }
100 |
101 | task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) {
102 | classifier = 'javadoc'
103 | from androidJavadocs.destinationDir
104 | }
105 |
106 | task androidSourcesJar(type: Jar) {
107 | classifier = 'sources'
108 | from android.sourceSets.main.java.sourceFiles
109 | }
110 |
111 | artifacts {
112 | archives androidSourcesJar
113 | archives androidJavadocsJar
114 | }
115 | }
--------------------------------------------------------------------------------
/example/src/main/java/com/github/pwittchen/networkevents/app/MainActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Piotr Wittchen
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.pwittchen.networkevents.app;
17 |
18 | import android.app.Activity;
19 | import android.net.wifi.ScanResult;
20 | import android.os.Bundle;
21 | import android.support.annotation.NonNull;
22 | import android.widget.ArrayAdapter;
23 | import android.widget.ListView;
24 | import android.widget.TextView;
25 | import android.widget.Toast;
26 | import com.github.pwittchen.networkevents.library.BusWrapper;
27 | import com.github.pwittchen.networkevents.library.NetworkEvents;
28 | import com.github.pwittchen.networkevents.library.event.ConnectivityChanged;
29 | import com.github.pwittchen.networkevents.library.event.WifiSignalStrengthChanged;
30 | import com.squareup.otto.Bus;
31 | import com.squareup.otto.Subscribe;
32 | import java.util.ArrayList;
33 | import java.util.List;
34 |
35 | public class MainActivity extends Activity {
36 | private BusWrapper busWrapper;
37 | private NetworkEvents networkEvents;
38 |
39 | private TextView connectivityStatus;
40 | private TextView mobileNetworkType;
41 | private ListView accessPoints;
42 |
43 | @Subscribe @SuppressWarnings("unused") public void onEvent(ConnectivityChanged event) {
44 | connectivityStatus.setText(event.getConnectivityStatus().toString());
45 | mobileNetworkType.setText(event.getMobileNetworkType().toString());
46 | }
47 |
48 | @Subscribe @SuppressWarnings("unused") public void onEvent(WifiSignalStrengthChanged event) {
49 | List wifiScanResults = new ArrayList<>();
50 |
51 | for (ScanResult scanResult : event.getWifiScanResults()) {
52 | wifiScanResults.add(scanResult.SSID);
53 | }
54 |
55 | int itemLayoutId = android.R.layout.simple_list_item_1;
56 | accessPoints.setAdapter(new ArrayAdapter<>(this, itemLayoutId, wifiScanResults));
57 | String message = getString(R.string.wifi_signal_strength_changed);
58 | Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
59 | }
60 |
61 | @Override protected void onCreate(Bundle savedInstanceState) {
62 | super.onCreate(savedInstanceState);
63 | setContentView(R.layout.activity_main);
64 | connectivityStatus = (TextView) findViewById(R.id.connectivity_status);
65 | mobileNetworkType = (TextView) findViewById(R.id.mobile_network_type);
66 | accessPoints = (ListView) findViewById(R.id.access_points);
67 | busWrapper = getOttoBusWrapper(new Bus());
68 | networkEvents = new NetworkEvents(getApplicationContext(), busWrapper).enableInternetCheck()
69 | .enableWifiScan();
70 | }
71 |
72 | @NonNull private BusWrapper getOttoBusWrapper(final Bus bus) {
73 | return new BusWrapper() {
74 | @Override public void register(Object object) {
75 | bus.register(object);
76 | }
77 |
78 | @Override public void unregister(Object object) {
79 | bus.unregister(object);
80 | }
81 |
82 | @Override public void post(Object event) {
83 | bus.post(event);
84 | }
85 | };
86 | }
87 |
88 | @Override protected void onResume() {
89 | super.onResume();
90 | busWrapper.register(this);
91 | networkEvents.register();
92 | }
93 |
94 | @Override protected void onPause() {
95 | super.onPause();
96 | busWrapper.unregister(this);
97 | networkEvents.unregister();
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/example-greenrobot-bus/src/main/java/com/github/pwittchen/networkevents/greenrobot/app/MainActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Piotr Wittchen
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.pwittchen.networkevents.greenrobot.app;
17 |
18 | import android.app.Activity;
19 | import android.net.wifi.ScanResult;
20 | import android.os.Bundle;
21 | import android.support.annotation.NonNull;
22 | import android.widget.ArrayAdapter;
23 | import android.widget.ListView;
24 | import android.widget.TextView;
25 | import android.widget.Toast;
26 | import com.github.pwittchen.networkevents.library.BusWrapper;
27 | import com.github.pwittchen.networkevents.library.NetworkEvents;
28 | import com.github.pwittchen.networkevents.library.event.ConnectivityChanged;
29 | import com.github.pwittchen.networkevents.library.event.WifiSignalStrengthChanged;
30 | import org.greenrobot.eventbus.EventBus;
31 | import org.greenrobot.eventbus.Subscribe;
32 | import java.util.ArrayList;
33 | import java.util.List;
34 |
35 | public class MainActivity extends Activity {
36 | private BusWrapper busWrapper;
37 | private NetworkEvents networkEvents;
38 |
39 | private TextView connectivityStatus;
40 | private TextView mobileNetworkType;
41 | private ListView accessPoints;
42 |
43 | @SuppressWarnings("unused") @Subscribe public void onEvent(ConnectivityChanged event) {
44 | connectivityStatus.setText(event.getConnectivityStatus().toString());
45 | mobileNetworkType.setText(event.getMobileNetworkType().toString());
46 | }
47 |
48 | @SuppressWarnings("unused") @Subscribe public void onEvent(WifiSignalStrengthChanged event) {
49 | List wifiScanResults = new ArrayList<>();
50 |
51 | for (ScanResult scanResult : event.getWifiScanResults()) {
52 | wifiScanResults.add(scanResult.SSID);
53 | }
54 |
55 | int itemLayoutId = android.R.layout.simple_list_item_1;
56 | accessPoints.setAdapter(new ArrayAdapter<>(this, itemLayoutId, wifiScanResults));
57 | String message = getString(R.string.wifi_signal_strength_changed);
58 | Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
59 | }
60 |
61 | @Override protected void onCreate(Bundle savedInstanceState) {
62 | super.onCreate(savedInstanceState);
63 | setContentView(R.layout.activity_main);
64 | connectivityStatus = (TextView) findViewById(R.id.connectivity_status);
65 | mobileNetworkType = (TextView) findViewById(R.id.mobile_network_type);
66 | accessPoints = (ListView) findViewById(R.id.access_points);
67 | final EventBus bus = new EventBus();
68 | busWrapper = getGreenRobotBusWrapper(bus);
69 | networkEvents = new NetworkEvents(getApplicationContext(), busWrapper).enableInternetCheck()
70 | .enableWifiScan();
71 | }
72 |
73 | @NonNull private BusWrapper getGreenRobotBusWrapper(final EventBus bus) {
74 | return new BusWrapper() {
75 | @Override public void register(Object object) {
76 | bus.register(object);
77 | }
78 |
79 | @Override public void unregister(Object object) {
80 | bus.unregister(object);
81 | }
82 |
83 | @Override public void post(Object event) {
84 | bus.post(event);
85 | }
86 | };
87 | }
88 |
89 | @Override protected void onStart() {
90 | super.onStart();
91 | busWrapper.register(this);
92 | networkEvents.register();
93 | }
94 |
95 | @Override protected void onStop() {
96 | busWrapper.unregister(this);
97 | networkEvents.unregister();
98 | super.onStop();
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/network-events-library/src/androidTest/java/com/github/pwittchen/networkevents/library/receiver/InternetConnectionChangeReceiverTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Piotr Wittchen
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.pwittchen.networkevents.library.receiver;
17 |
18 | import android.content.Context;
19 | import android.support.test.runner.AndroidJUnit4;
20 |
21 | import com.github.pwittchen.networkevents.library.ConnectivityStatus;
22 | import com.github.pwittchen.networkevents.library.BusWrapper;
23 | import com.github.pwittchen.networkevents.library.logger.Logger;
24 | import com.github.pwittchen.networkevents.library.NetworkState;
25 | import com.github.pwittchen.networkevents.library.utils.OttoBusWrapper;
26 | import com.github.pwittchen.networkevents.library.utils.TestUtils;
27 | import com.github.pwittchen.networkevents.library.event.ConnectivityChanged;
28 | import com.squareup.otto.Bus;
29 | import com.squareup.otto.ThreadEnforcer;
30 |
31 | import org.junit.After;
32 | import org.junit.Before;
33 | import org.junit.Test;
34 | import org.junit.runner.RunWith;
35 | import org.mockito.Mockito;
36 |
37 | import java.util.ArrayList;
38 | import java.util.List;
39 |
40 | import static com.google.common.truth.Truth.assertThat;
41 |
42 | @RunWith(AndroidJUnit4.class) public class InternetConnectionChangeReceiverTest {
43 |
44 | private InternetConnectionChangeReceiver receiver;
45 | private BusWrapper busWrapper;
46 | private List connectivityChangeEvents;
47 |
48 | @Before public void setUp() throws Exception {
49 | this.busWrapper = new OttoBusWrapper(new Bus(ThreadEnforcer.ANY));
50 | Logger logger = Mockito.mock(Logger.class);
51 | Context context = Mockito.mock(Context.class);
52 | this.receiver = new InternetConnectionChangeReceiver(busWrapper, logger, context);
53 | this.connectivityChangeEvents = new ArrayList<>();
54 | }
55 |
56 | @After public void tearDown() throws Exception {
57 | connectivityChangeEvents.clear();
58 | }
59 |
60 | @Test public void testShouldReceiveAnEventWhenDeviceIsConnectedToWifiWithInternetAccess()
61 | throws InterruptedException {
62 | // given
63 | connectivityChangeEvents.clear();
64 | boolean connectedToInternet = true;
65 | NetworkState.status = ConnectivityStatus.UNKNOWN;
66 | Object eventCatcher = TestUtils.getConnectivityEventCatcher(connectivityChangeEvents);
67 | busWrapper.register(eventCatcher);
68 |
69 | // when
70 | onPostReceiveAndSleep(connectedToInternet);
71 |
72 | // then
73 | ConnectivityStatus expectedConnectivityStatus = ConnectivityStatus.WIFI_CONNECTED_HAS_INTERNET;
74 | assertExpectedStatusEqualsCurrent(expectedConnectivityStatus, eventCatcher);
75 | }
76 |
77 | @Test public void testShouldReceiveAnEventWhenDeviceIsConnectedToWifiWithNoInternetAccess()
78 | throws InterruptedException {
79 | // given
80 | connectivityChangeEvents.clear();
81 | boolean connectedToInternet = false;
82 | NetworkState.status = ConnectivityStatus.UNKNOWN;
83 | Object eventCatcher = TestUtils.getConnectivityEventCatcher(connectivityChangeEvents);
84 | busWrapper.register(eventCatcher);
85 |
86 | // when
87 | onPostReceiveAndSleep(connectedToInternet);
88 |
89 | // then
90 | ConnectivityStatus expectedStatus = ConnectivityStatus.WIFI_CONNECTED_HAS_NO_INTERNET;
91 | assertExpectedStatusEqualsCurrent(expectedStatus, eventCatcher);
92 | }
93 |
94 | private void onPostReceiveAndSleep(boolean connectedToInternet) throws InterruptedException {
95 | // in this case, for unit tests, we should pass Context as null in onPostReceive(...)
96 | // to avoid non-deterministic calls to Android SDK
97 | receiver.onPostReceive(connectedToInternet, null);
98 | Thread.sleep(2000); // wait a while for async operation
99 | }
100 |
101 | private void assertExpectedStatusEqualsCurrent(ConnectivityStatus status, Object eventCatcher) {
102 | ConnectivityStatus currentStatus = connectivityChangeEvents.get(0).getConnectivityStatus();
103 | assertThat(status).isEqualTo(currentStatus);
104 | busWrapper.unregister(eventCatcher);
105 | }
106 | }
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # For Cygwin, ensure paths are in UNIX format before anything is touched.
46 | if $cygwin ; then
47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
48 | fi
49 |
50 | # Attempt to set APP_HOME
51 | # Resolve links: $0 may be a link
52 | PRG="$0"
53 | # Need this for relative symlinks.
54 | while [ -h "$PRG" ] ; do
55 | ls=`ls -ld "$PRG"`
56 | link=`expr "$ls" : '.*-> \(.*\)$'`
57 | if expr "$link" : '/.*' > /dev/null; then
58 | PRG="$link"
59 | else
60 | PRG=`dirname "$PRG"`"/$link"
61 | fi
62 | done
63 | SAVED="`pwd`"
64 | cd "`dirname \"$PRG\"`/" >&-
65 | APP_HOME="`pwd -P`"
66 | cd "$SAVED" >&-
67 |
68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
69 |
70 | # Determine the Java command to use to start the JVM.
71 | if [ -n "$JAVA_HOME" ] ; then
72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
73 | # IBM's JDK on AIX uses strange locations for the executables
74 | JAVACMD="$JAVA_HOME/jre/sh/java"
75 | else
76 | JAVACMD="$JAVA_HOME/bin/java"
77 | fi
78 | if [ ! -x "$JAVACMD" ] ; then
79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
80 |
81 | Please set the JAVA_HOME variable in your environment to match the
82 | location of your Java installation."
83 | fi
84 | else
85 | JAVACMD="java"
86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
87 |
88 | Please set the JAVA_HOME variable in your environment to match the
89 | location of your Java installation."
90 | fi
91 |
92 | # Increase the maximum file descriptors if we can.
93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
94 | MAX_FD_LIMIT=`ulimit -H -n`
95 | if [ $? -eq 0 ] ; then
96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
97 | MAX_FD="$MAX_FD_LIMIT"
98 | fi
99 | ulimit -n $MAX_FD
100 | if [ $? -ne 0 ] ; then
101 | warn "Could not set maximum file descriptor limit: $MAX_FD"
102 | fi
103 | else
104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
105 | fi
106 | fi
107 |
108 | # For Darwin, add options to specify how the application appears in the dock
109 | if $darwin; then
110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
111 | fi
112 |
113 | # For Cygwin, switch paths to Windows format before running java
114 | if $cygwin ; then
115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
158 | function splitJvmOpts() {
159 | JVM_OPTS=("$@")
160 | }
161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
163 |
164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
165 |
--------------------------------------------------------------------------------
/network-events-library/src/androidTest/java/com/github/pwittchen/networkevents/library/receiver/NetworkConnectionChangeReceiverTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Piotr Wittchen
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.pwittchen.networkevents.library.receiver;
17 |
18 | import android.content.Context;
19 | import android.support.test.runner.AndroidJUnit4;
20 |
21 | import com.github.pwittchen.networkevents.library.BusWrapper;
22 | import com.github.pwittchen.networkevents.library.ConnectivityStatus;
23 | import com.github.pwittchen.networkevents.library.NetworkState;
24 | import com.github.pwittchen.networkevents.library.event.ConnectivityChanged;
25 | import com.github.pwittchen.networkevents.library.internet.OnlineChecker;
26 | import com.github.pwittchen.networkevents.library.logger.Logger;
27 | import com.github.pwittchen.networkevents.library.utils.OttoBusWrapper;
28 | import com.github.pwittchen.networkevents.library.utils.TestUtils;
29 | import com.squareup.otto.Bus;
30 | import com.squareup.otto.ThreadEnforcer;
31 |
32 | import org.junit.After;
33 | import org.junit.Before;
34 | import org.junit.Test;
35 | import org.junit.runner.RunWith;
36 | import org.mockito.Mockito;
37 |
38 | import java.util.ArrayList;
39 | import java.util.List;
40 |
41 | import static com.google.common.truth.Truth.assertThat;
42 |
43 | @RunWith(AndroidJUnit4.class) public class NetworkConnectionChangeReceiverTest {
44 |
45 | private NetworkConnectionChangeReceiver receiver;
46 | private BusWrapper busWrapper;
47 | private List connectivityChangeEvents;
48 |
49 | @Before public void setUp() throws Exception {
50 | this.busWrapper = new OttoBusWrapper(new Bus(ThreadEnforcer.ANY));
51 | Logger logger = Mockito.mock(Logger.class);
52 | Context context = Mockito.mock(Context.class);
53 | OnlineChecker onlineChecker = Mockito.mock(OnlineChecker.class);
54 | this.receiver = new NetworkConnectionChangeReceiver(busWrapper, logger, context, onlineChecker);
55 | this.connectivityChangeEvents = new ArrayList<>();
56 | }
57 |
58 | @After public void tearDown() throws Exception {
59 | connectivityChangeEvents.clear();
60 | }
61 |
62 | @Test public void testReceiverShouldReceiveAnEventOnConnectivityChange() throws Exception {
63 | // given
64 | connectivityChangeEvents.clear();
65 | NetworkState.status = ConnectivityStatus.UNKNOWN;
66 | Object eventCatcher = TestUtils.getConnectivityEventCatcher(connectivityChangeEvents);
67 | busWrapper.register(eventCatcher);
68 | ConnectivityStatus connectivityStatus = ConnectivityStatus.OFFLINE;
69 |
70 | // when
71 | onPostReceiveAndSleep(connectivityStatus);
72 |
73 | // then
74 | assertThat(connectivityChangeEvents).isNotEmpty();
75 | busWrapper.unregister(eventCatcher);
76 | }
77 |
78 | @Test public void testReceiverShouldReceiveAnEventWhenGoingOffline() throws Exception {
79 | // given
80 | connectivityChangeEvents.clear();
81 | Object eventCatcher = TestUtils.getConnectivityEventCatcher(connectivityChangeEvents);
82 | setUnknownNetworkStatusAndRegisterBus(eventCatcher);
83 | ConnectivityStatus expectedConnectivityStatus = ConnectivityStatus.OFFLINE;
84 |
85 | // when
86 | onPostReceiveAndSleep(expectedConnectivityStatus);
87 |
88 | // then
89 | assertExpectedStatusEqualsCurrent(expectedConnectivityStatus, eventCatcher);
90 | }
91 |
92 | @Test public void testReceiverShouldReceiveAnEventWhenGoingOnlineViaWifi() throws Exception {
93 | // given
94 | connectivityChangeEvents.clear();
95 | Object eventCatcher = TestUtils.getConnectivityEventCatcher(connectivityChangeEvents);
96 | setUnknownNetworkStatusAndRegisterBus(eventCatcher);
97 | ConnectivityStatus expectedConnectivityStatus = ConnectivityStatus.WIFI_CONNECTED;
98 |
99 | // when
100 | onPostReceiveAndSleep(expectedConnectivityStatus);
101 |
102 | // then
103 | assertExpectedStatusEqualsCurrent(expectedConnectivityStatus, eventCatcher);
104 | }
105 |
106 | @Test public void testReceiverShouldReceiveAnEventWhenGoingOnlineViaMobile() throws Exception {
107 | // given
108 | connectivityChangeEvents.clear();
109 | Object eventCatcher = TestUtils.getConnectivityEventCatcher(connectivityChangeEvents);
110 | setUnknownNetworkStatusAndRegisterBus(eventCatcher);
111 | ConnectivityStatus expectedConnectivityStatus = ConnectivityStatus.MOBILE_CONNECTED;
112 |
113 | // when
114 | onPostReceiveAndSleep(expectedConnectivityStatus);
115 |
116 | // then
117 | assertExpectedStatusEqualsCurrent(expectedConnectivityStatus, eventCatcher);
118 | }
119 |
120 | private void onPostReceiveAndSleep(ConnectivityStatus status) throws InterruptedException {
121 | receiver.onPostReceive(status);
122 | Thread.sleep(2000); // wait a while for async operation
123 | }
124 |
125 | private void setUnknownNetworkStatusAndRegisterBus(Object eventCatcher) {
126 | NetworkState.status = ConnectivityStatus.UNKNOWN;
127 | busWrapper.register(eventCatcher);
128 | }
129 |
130 | private void assertExpectedStatusEqualsCurrent(ConnectivityStatus status, Object eventCatcher) {
131 | ConnectivityStatus currentStatus = connectivityChangeEvents.get(0).getConnectivityStatus();
132 | assertThat(status).isEqualTo(currentStatus);
133 | busWrapper.unregister(eventCatcher);
134 | }
135 | }
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | CHANGELOG
2 | =========
3 |
4 | v. 2.1.6
5 | --------
6 | *18 Jul 2016*
7 |
8 | - added customization of the ping parameters via method `NetworkEvents setPingParameters(String host, int port, int timeoutInMs)`
9 |
10 | v. 2.1.5
11 | --------
12 | *18 Jul 2016*
13 |
14 | - added the private constructor to `NetworkHelper` class
15 |
16 | v. 2.1.4
17 | --------
18 | *17 Jul 2016*
19 |
20 | - changed implementation of the `OnlineChecker` in `OnlineCheckerImpl` class. Now it pings remote host.
21 | - added `android.permission.INTERNET` to `AndroidManifest.xml`
22 | - added back `NetworkHelper` class with static method `boolean isConnectedToWiFiOrMobileNetwork(context)`
23 | - updated sample apps
24 |
25 | v. 2.1.3
26 | --------
27 | *10 Jan 2016*
28 |
29 | - Due to memory leak in WifiManager reported in issue [43945](https://code.google.com/p/android/issues/detail?id=43945) in Android issue tracker replaced Activity Context with Application Context in sample apps and added appropriate note in `README.md`
30 | - added `ACCESS_COARSE_LOCATION` permission to `AndroidManifest.xml` to be able to scan WiFi access points on Android 6
31 |
32 | v. 2.1.2
33 | --------
34 | *04 Oct 2015*
35 |
36 | - bumped target SDK version to 23
37 | - bumped buildToolsVersion to 23.0.1
38 | - removed `CHANGE_NETWORK_STATE` and `INTERNET` permissions from `AndroidManifest.xml`, because they're no longer required
39 |
40 | v. 2.1.1
41 | --------
42 | *13 Sep 2015*
43 |
44 | - updated `InternetConnectionChangeReceiver` class and its API
45 | - fixed failing unit tests
46 | - all changes were provided in a single commit https://github.com/pwittchen/NetworkEvents/commit/2f6999c5cd45ba220f615580e64bfee9e6cc8089
47 |
48 | v. 2.1.0
49 | --------
50 | *13 Sep 2015*
51 |
52 | replaced `networkInfo.isConnectedOrConnecting()` with `networkInfo.isConnected()` in `isOnline(context)` method in `OnlineCheckerImpl` class.
53 |
54 | v. 2.0.1
55 | --------
56 | *09 Aug 2015*
57 |
58 | replaced `networkInfo.isConnectedOrConnecting()` with `networkInfo.isConnected()` in `isOnline(context)` method in `OnlineCheckerImpl` class.
59 |
60 | v. 2.0.0
61 | --------
62 | *31 Jul 2015*
63 |
64 | * removed `withPingUrl(url)` method
65 | * removed `withPingTimeout()` method
66 | * removed `withoutPing()` method
67 | * removed `withoutWifiAccessPointsScan()` method
68 | * removed Otto dependency (now, it's available only for unit tests)
69 | * removed `example-disabling-ping-and-wifi-scan` app sample
70 | * removed `example-ping-customization` app sample
71 | * removed `NetworkHelper` class and moved its method to specific classes with changed scope
72 | * moved permissions to Manifest of library
73 | * disabled WiFi scan by default
74 | * disabled Internet connection check by default
75 | * added `BusWrapper`, which is abstraction for Event Bus required by `NetworkEvents` object
76 | * added `example-greenrobot-bus` app sample
77 | * added `enableWifiScan()` method
78 | * added `enableInternetCheck()` method
79 | * added `getWifiScanResults()` method in WifiSignalStrengthChanged event
80 | * added `getMobileNetworkType()` method in ConnectivityChanged event
81 | * added JavaDoc at: http://pwittchen.github.io/NetworkEvents/
82 | * updated existing sample applications
83 | * updated documentation in `README.md` and library code
84 |
85 | v. 1.0.5
86 | --------
87 | *13 May 2015*
88 |
89 | In this version, we can customize `NetworkEvents` object. E.g. we can set our own ping url and ping timeout:
90 |
91 | ```java
92 | networkEvents = new NetworkEvents(this, bus)
93 | .withPingUrl("http://www.android.com")
94 | .withPingTimeout(50 * 1000);
95 | ```
96 | We can also disable ping or Wifi Access Points Scan:
97 | ```java
98 | networkEvents = new NetworkEvents(this, bus)
99 | .withoutPing()
100 | .withoutWifiAccessPointsScan();
101 | ```
102 | In the main repository, we can find new examples of applications showing how to use these methods.
103 | In addition, internal elements of code (especially `NetworkEvents` class) were updated and new unit tests were created.
104 |
105 | v. 1.0.4
106 | --------
107 | *21 Mar 2015*
108 |
109 | * migrated unit tests to AndroidJUnit4 runner
110 | * added Google Truth assertions for unit tests
111 | * added Mockito library for creating mocks in unit tests
112 | * fixed bug with `EOFException` in `HttpURLConnection` in `ping` method inside `NetworkHelper` class
113 | * refactored code to make it more testable and loosely coupled
114 |
115 | v. 1.0.3
116 | --------
117 | *07 Mar 2015*
118 |
119 | - updated `ping` method in `NetworkHelper` class to more reliable
120 | - added unit tests
121 | - refactored code due to unit tests
122 | - added missing comments with license
123 | - updated Android Build Tools to 1.1.0
124 | - removed unused `getWifiInfo()` method from `NetworkHelper` class
125 | - updated `travis.yml` file for CI
126 | - left public API unchanged
127 |
128 | v. 1.0.2
129 | --------
130 | *14 Feb 2015*
131 |
132 | - improved ping method in NetworkHelper class
133 | - detection of Internet access in WiFi network works faster and is more reliable
134 | - added example of usage of the library with Dagger
135 |
136 | v. 1.0.1
137 | --------
138 | *31 Jan 2015*
139 |
140 | * added support for API 9 (Android 2.3 GINGERBREAD) and above
141 | * increased code immutability
142 | * removed dependency to unused appcompat library
143 | * performed small code refactoring and reformatting
144 |
145 | v. 1.0.0
146 | --------
147 | *30 Jan 2015*
148 |
149 | First version of the library is available in Maven Central Repository.
150 | It supports API 15 (Android 4.0.3 - ICE_CREAM_SANDWICH_MR1) and above.
151 |
152 | Library has the following features:
153 | * listening connection state (WiFi, WiFi with Internet access, mobile network, off-line)
154 | * listening change of the WiFi signal strength
155 | * informing about the network events via Otto Event Bus
156 |
157 | The following bug was fixed:
158 | * Pushing several events twice to the bus when event occurred once
159 |
--------------------------------------------------------------------------------
/network-events-library/src/main/java/com/github/pwittchen/networkevents/library/NetworkEvents.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Piotr Wittchen
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.pwittchen.networkevents.library;
17 |
18 | import android.content.Context;
19 | import android.content.IntentFilter;
20 | import android.net.ConnectivityManager;
21 | import android.net.wifi.WifiManager;
22 | import com.github.pwittchen.networkevents.library.internet.OnlineChecker;
23 | import com.github.pwittchen.networkevents.library.internet.OnlineCheckerImpl;
24 | import com.github.pwittchen.networkevents.library.logger.Logger;
25 | import com.github.pwittchen.networkevents.library.logger.NetworkEventsLogger;
26 | import com.github.pwittchen.networkevents.library.receiver.InternetConnectionChangeReceiver;
27 | import com.github.pwittchen.networkevents.library.receiver.NetworkConnectionChangeReceiver;
28 | import com.github.pwittchen.networkevents.library.receiver.WifiSignalStrengthChangeReceiver;
29 |
30 | /**
31 | * NetworkEvents - Android library listening network events.
32 | * It is able to detect ConnectivityStatus when it changes:
33 | *
34 | * - WIFI_CONNECTED("connected to WiFi")
35 | * - WIFI_CONNECTED_HAS_INTERNET("connected to WiFi (Internet available)")
36 | * - WIFI_CONNECTED_HAS_NO_INTERNET("connected to WiFi (Internet not available)")
37 | * - MOBILE_CONNECTED("connected to mobile network")
38 | * - OFFLINE("offline")
39 | *
40 | * In addition it is able to detect situation when strength
41 | * of the Wifi signal was changed with WifiSignalStrengthChanged event.
42 | */
43 | public final class NetworkEvents {
44 | private boolean wifiAccessPointsScanEnabled = false;
45 | private final Context context;
46 | private final NetworkConnectionChangeReceiver networkConnectionChangeReceiver;
47 | private final InternetConnectionChangeReceiver internetConnectionChangeReceiver;
48 | private final WifiSignalStrengthChangeReceiver wifiSignalStrengthChangeReceiver;
49 | private final OnlineChecker onlineChecker;
50 |
51 | /**
52 | * Initializes NetworkEvents object
53 | * with NetworkEventsLogger as default logger.
54 | *
55 | * @param context Android context
56 | * @param busWrapper Wrapper for event bus
57 | */
58 | public NetworkEvents(Context context, BusWrapper busWrapper) {
59 | this(context, busWrapper, new NetworkEventsLogger());
60 | }
61 |
62 | /**
63 | * Initializes NetworkEvents object.
64 | *
65 | * @param context Android context
66 | * @param busWrapper Wrapper fo event bus
67 | * @param logger message logger (NetworkEventsLogger logs messages to LogCat)
68 | */
69 | public NetworkEvents(Context context, BusWrapper busWrapper, Logger logger) {
70 | checkNotNull(context, "context == null");
71 | checkNotNull(busWrapper, "busWrapper == null");
72 | checkNotNull(logger, "logger == null");
73 | this.context = context;
74 | this.onlineChecker = new OnlineCheckerImpl(context);
75 | this.networkConnectionChangeReceiver =
76 | new NetworkConnectionChangeReceiver(busWrapper, logger, context, onlineChecker);
77 | this.internetConnectionChangeReceiver =
78 | new InternetConnectionChangeReceiver(busWrapper, logger, context);
79 | this.wifiSignalStrengthChangeReceiver =
80 | new WifiSignalStrengthChangeReceiver(busWrapper, logger, context);
81 | }
82 |
83 | /**
84 | * Enables wifi access points scan.
85 | * When it's not called, WifiSignalStrengthChanged event will never occur.
86 | *
87 | * @return NetworkEvents object
88 | */
89 | public NetworkEvents enableWifiScan() {
90 | this.wifiAccessPointsScanEnabled = true;
91 | return this;
92 | }
93 |
94 | /**
95 | * Enables internet connection check.
96 | * when it's not called, WIFI_CONNECTED_HAS_INTERNET
97 | * and WIFI_CONNECTED_HAS_NO_INTERNET ConnectivityStatus will never be set
98 | * Please, be careful! Internet connection check may contain bugs
99 | * that's why it's disabled by default.
100 | *
101 | * @return NetworkEvents object
102 | */
103 | public NetworkEvents enableInternetCheck() {
104 | networkConnectionChangeReceiver.enableInternetCheck();
105 | return this;
106 | }
107 |
108 | /**
109 | * Sets ping parameters of the host used to check Internet connection.
110 | * If it's not set, library will use default ping parameters.
111 | *
112 | * @param host host to be pinged
113 | * @param port port of the host
114 | * @param timeoutInMs timeout in milliseconds
115 | * @return NetworkEvents object
116 | */
117 | public NetworkEvents setPingParameters(String host, int port, int timeoutInMs) {
118 | onlineChecker.setPingParameters(host, port, timeoutInMs);
119 | return this;
120 | }
121 |
122 | /**
123 | * Registers NetworkEvents.
124 | * It should be executed in onCreate() method in activity
125 | * or during creating instance of class extending Application.
126 | */
127 | public void register() {
128 | registerNetworkConnectionChangeReceiver();
129 | registerInternetConnectionChangeReceiver();
130 |
131 | if (wifiAccessPointsScanEnabled) {
132 | registerWifiSignalStrengthChangeReceiver();
133 | // start WiFi scan in order to refresh access point list
134 | // if this won't be called WifiSignalStrengthChanged may never occur
135 | WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
136 | wifiManager.startScan();
137 | }
138 | }
139 |
140 | /**
141 | * Unregisters NetworkEvents.
142 | * It should be executed in onDestroy() method in activity
143 | * or during destroying instance of class extending Application.
144 | */
145 | public void unregister() {
146 | context.unregisterReceiver(networkConnectionChangeReceiver);
147 | context.unregisterReceiver(internetConnectionChangeReceiver);
148 | if (wifiAccessPointsScanEnabled) {
149 | context.unregisterReceiver(wifiSignalStrengthChangeReceiver);
150 | }
151 | }
152 |
153 | private void registerNetworkConnectionChangeReceiver() {
154 | IntentFilter filter = new IntentFilter();
155 | filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
156 | filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
157 | context.registerReceiver(networkConnectionChangeReceiver, filter);
158 | }
159 |
160 | private void registerInternetConnectionChangeReceiver() {
161 | IntentFilter filter = new IntentFilter();
162 | filter.addAction(InternetConnectionChangeReceiver.INTENT);
163 | context.registerReceiver(internetConnectionChangeReceiver, filter);
164 | }
165 |
166 | private void registerWifiSignalStrengthChangeReceiver() {
167 | IntentFilter filter = new IntentFilter(WifiManager.RSSI_CHANGED_ACTION);
168 | context.registerReceiver(wifiSignalStrengthChangeReceiver, filter);
169 | }
170 |
171 | private void checkNotNull(Object object, String message) {
172 | if (object == null) {
173 | throw new IllegalArgumentException(message);
174 | }
175 | }
176 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | NetworkEvents
2 | ===============================
3 | [](https://travis-ci.org/pwittchen/NetworkEvents)
4 | [](https://android-arsenal.com/details/1/1392)
5 | [](https://maven-badges.herokuapp.com/maven-central/com.github.pwittchen/networkevents)
6 |
7 | Android library listening network connection state and change of the WiFi signal strength with event bus.
8 |
9 | It works with any implementation of the Event Bus. In this repository you can find samples with Otto and GreenRobot's bus.
10 |
11 | min sdk version = 9
12 |
13 | JavaDoc is available at: http://pwittchen.github.io/NetworkEvents
14 |
15 | This project is deprecated!
16 | ---------------------------
17 |
18 | This library is now **deprecated** and **no longer maintained** in favor of the following libraries, which do the same job, but in the better way:
19 | - [**ReactiveNetwork**](https://github.com/pwittchen/ReactiveNetwork)
20 | - [**ReactiveWiFi**](https://github.com/pwittchen/ReactiveWiFi)
21 |
22 | Contents
23 | --------
24 | - [Overview](#overview)
25 | - [Usage](#usage)
26 | - [Initialize objects](#initialize-objects)
27 | - [NetworkEvents customization](#networkevents-customization)
28 | - [Custom logger](#custom-logger)
29 | - [Enabling WiFi scan](#enabling-wifi-scan)
30 | - [Enabling Internet connection check](#enabling-internet-connection-check)
31 | - [Customizing ping parameters](#customizing-ping-parameters)
32 | - [Register and unregister objects](#register-and-unregister-objects)
33 | - [Subscribe for the events](#subscribe-for-the-events)
34 | - [NetworkHelper](#networkhelper)
35 | - [Examples](#examples)
36 | - [Download](#download)
37 | - [Tests](#tests)
38 | - [Code style](#code-style)
39 | - [Who is using this library?](#who-is-using-this-library)
40 | - [License](#license)
41 |
42 | Overview
43 | --------
44 |
45 | Library is able to detect `ConnectivityStatus` when it changes.
46 |
47 | ```java
48 | public enum ConnectivityStatus {
49 | UNKNOWN("unknown"),
50 | WIFI_CONNECTED("connected to WiFi"),
51 | WIFI_CONNECTED_HAS_INTERNET("connected to WiFi (Internet available)"),
52 | WIFI_CONNECTED_HAS_NO_INTERNET("connected to WiFi (Internet not available)"),
53 | MOBILE_CONNECTED("connected to mobile network"),
54 | OFFLINE("offline");
55 | ...
56 | }
57 | ```
58 |
59 | In addition, it is able to detect situation when strength of the Wifi signal was changed with `WifiSignalStrengthChanged` event, when we [enable WiFi scanning](#enabling-wifi-scan).
60 |
61 | Library is able to detect `MobileNetworkType` when `ConnectivityStatus` changes to `MOBILE_CONNECTED`.
62 |
63 | ```java
64 | public enum MobileNetworkType {
65 | UNKNOWN("unknown"),
66 | LTE("LTE"),
67 | HSPAP("HSPAP"),
68 | EDGE("EDGE"),
69 | GPRS("GPRS");
70 | ...
71 | }
72 | ```
73 |
74 | Usage
75 | -----
76 |
77 | Appropriate permissions are already set in `AndroidManifest.xml` file for the library inside the `` tag.
78 | They don't need to be set inside the specific application, which uses library.
79 |
80 | ### Initialize objects
81 |
82 | In your activity add `BusWrapper` field, which wraps your Event Bus. You can use [Otto](http://square.github.io/otto/) as in this sample and then create `NetworkEvents` field.
83 |
84 | ```java
85 | private BusWrapper busWrapper;
86 | private NetworkEvents networkEvents;
87 | ```
88 |
89 | Create implementation of `BusWrapper`. You can use any event bus here. E.g. [GreenRobot's Event Bus](https://github.com/greenrobot/EventBus). In this example, we are wrapping Otto Event bus.
90 |
91 | ```java
92 | private BusWrapper getOttoBusWrapper(final Bus bus) {
93 | return new BusWrapper() {
94 | @Override public void register(Object object) {
95 | bus.register(object);
96 | }
97 |
98 | @Override public void unregister(Object object) {
99 | bus.unregister(object);
100 | }
101 |
102 | @Override public void post(Object event) {
103 | bus.post(event);
104 | }
105 | };
106 | }
107 | ```
108 |
109 | Initialize objects in `onCreate(Bundle savedInstanceState)` method.
110 |
111 | ```java
112 | @Override protected void onCreate(Bundle savedInstanceState) {
113 | super.onCreate(savedInstanceState);
114 | busWrapper = getOttoBusWrapper(new Bus());
115 | networkEvents = new NetworkEvents(context, busWrapper);
116 | }
117 | ```
118 |
119 | **Please note**: Due to memory leak in `WifiManager` reported
120 | in [issue 43945](https://code.google.com/p/android/issues/detail?id=43945) in Android issue tracker
121 | it's recommended to use Application Context instead of Activity Context.
122 |
123 | #### NetworkEvents Customization
124 |
125 | ##### Custom logger
126 |
127 | By default library logs messages about changed connectivity or WiFi signal strength to LogCat.
128 | We can create custom logger implementation in the following way:
129 |
130 | ```java
131 | networkEvents = new NetworkEvents(context, busWrapper, new Logger() {
132 | @Override public void log(String message) {
133 | // log your message here
134 | }
135 | });
136 | ```
137 |
138 | If we don't want to log anything, we can simply create empty implementation of the `Logger` interface, when `log(message)` method doesn't do anything.
139 |
140 | ##### enabling WiFi scan
141 |
142 | WiFi Access Points scanning is disabled by default. If Wifi Access Points Scan is not enabled, `WifiSignalStrengthChanged` event will never occur. You can enable it as follows:
143 |
144 | ```java
145 | networkEvents = new NetworkEvents(context, busWrapper)
146 | .enableWifiScan();
147 | ```
148 |
149 | ##### enabling Internet connection check
150 |
151 | Internet connection check is disabled by default. If Internet check is disabled, status `WIFI_CONNECTED_HAS_INTERNET` and `WIFI_CONNECTED_HAS_NO_INTERNET` won't be set.
152 | If internet check is enabled `WIFI_CONNECTED` status will never occur (from version 2.1.0). The only statuses, which may occur after connecting to WiFi after enabling this option are `WIFI_CONNECTED_HAS_INTERNET` and `WIFI_CONNECTED_HAS_NO_INTERNET`.
153 |
154 | You can enable internet check as follows:
155 |
156 | ```java
157 | networkEvents = new NetworkEvents(context, busWrapper)
158 | .enableInternetCheck();
159 | ```
160 |
161 | ##### customizing ping parameters
162 |
163 | You can customize ping parameters used to check Internet connectivity. You can set your own host, port and ping timeout in milliseconds as follows:
164 |
165 | ```java
166 | networkEvents = new NetworkEvents(context, busWrapper)
167 | .setPingParameters("www.anyhostyouwant.com", 80, 30)
168 | ```
169 |
170 | In the example presented above, library will ping www.anyhostyouwant.com on port 80 with timeout equal to 30 milliseconds.
171 |
172 | ### Register and unregister objects
173 |
174 | We have to register and unregister objects in Activity Lifecycle.
175 |
176 | In case of different Event Buses, we have to do it differently.
177 |
178 | #### Otto Bus
179 |
180 | Register `BusWrapper` and `NetworkEvents` in `onResume()` method and unregister them in `onPause()` method.
181 |
182 | ```java
183 | @Override protected void onResume() {
184 | super.onResume();
185 | busWrapper.register(this);
186 | networkEvents.register();
187 | }
188 |
189 | @Override protected void onPause() {
190 | super.onPause();
191 | busWrapper.unregister(this);
192 | networkEvents.unregister();
193 | }
194 | ```
195 |
196 | #### GreenRobot's Bus
197 |
198 | Register `BusWrapper` and `NetworkEvents` in `onStart()` method and unregister them in `onStop()` method.
199 |
200 | ```java
201 | @Override protected void onStart() {
202 | super.onStart();
203 | busWrapper.register(this);
204 | networkEvents.register();
205 | }
206 |
207 | @Override protected void onStop() {
208 | busWrapper.unregister(this);
209 | networkEvents.unregister();
210 | super.onStop();
211 | }
212 | ```
213 |
214 | ### Subscribe for the events
215 |
216 | For Otto Event Bus `@Subscribe` annotations are required, but we don't have to use them in case of using library with GreenRobot's Event Bus.
217 |
218 | ```java
219 | @Subscribe public void onEvent(ConnectivityChanged event) {
220 | // get connectivity status from event.getConnectivityStatus()
221 | // or mobile network type via event.getMobileNetworkType()
222 | // and do whatever you want
223 | }
224 |
225 | @Subscribe public void onEvent(WifiSignalStrengthChanged event) {
226 | // do whatever you want - e.g. read fresh list of access points
227 | // via event.getWifiScanResults() method
228 | }
229 | ```
230 |
231 | ### NetworkHelper
232 |
233 | Library has additional class called `NetworkHelper` with static method, which can be used for determining if device is connected to WiFi or mobile network:
234 |
235 | ```java
236 | NetworkHelper.isConnectedToWiFiOrMobileNetwork(context)
237 | ```
238 |
239 | It returns `true` if device is connected to one of mentioned networks and `false` if not.
240 |
241 | Examples
242 | --------
243 |
244 | * Look at `MainActivity` in application located in `example` directory to see how this library works with Otto Event Bus.
245 | * Example presenting how to use this library with GreenRobot's Event Bus is presented in `example-greenrobot-bus ` directory
246 |
247 | Download
248 | --------
249 |
250 | You can depend on the library through Maven:
251 |
252 | ```xml
253 |
254 | com.github.pwittchen
255 | networkevents
256 | 2.1.6
257 |
258 | ```
259 |
260 | or through Gradle:
261 |
262 | ```groovy
263 | dependencies {
264 | compile 'com.github.pwittchen:networkevents:2.1.6'
265 | }
266 | ```
267 |
268 | **Remember to add dependency to the Event Bus, which you are using.**
269 |
270 | In case of Otto, add the following dependency through Maven:
271 |
272 | ```xml
273 |
274 | com.squareup
275 | otto
276 | 1.3.8
277 |
278 | ```
279 |
280 | or through Gradle:
281 |
282 | ```groovy
283 | dependencies {
284 | compile 'com.squareup:otto:1.3.8'
285 | }
286 | ```
287 |
288 | You can also use **GreenRobot's Event Bus** or **any Event Bus you want**.
289 |
290 | Tests
291 | -----
292 |
293 | Tests are available in `network-events-library/src/androidTest/java/` directory and can be executed on emulator or Android device from Android Studio or CLI with the following command:
294 |
295 | ```
296 | ./gradlew connectedCheck
297 | ```
298 |
299 | Test coverage report can be generated with the following command:
300 |
301 | ```
302 | ./gradlew createDebugCoverageReport
303 | ```
304 |
305 | In order to generate report, emulator or Android device needs to be connected to the computer.
306 | Report will be generated in the `network-events-library/build/outputs/reports/coverage/debug/` directory.
307 |
308 | Code style
309 | ----------
310 |
311 | 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.
312 |
313 | Who is using this library?
314 | --------------------------
315 | - [Ceerus - app providing secure voice, video and messaging with technology developed through research with the UK Ministry of Defence](https://play.google.com/store/apps/details?id=com.sqrsystems.anchor)
316 | - [FP Mobile](https://play.google.com/store/apps/details?id=com.fp.fpmobile)
317 | - [BetterX-Android](https://github.com/eliasall/BetterX-Android)
318 |
319 | Are you using this library in your app and want to be listed here? Send me a Pull Request or an e-mail to piotr@wittchen.biz.pl
320 |
321 |
322 | License
323 | -------
324 |
325 | Copyright 2015 Piotr Wittchen
326 |
327 | Licensed under the Apache License, Version 2.0 (the "License");
328 | you may not use this file except in compliance with the License.
329 | You may obtain a copy of the License at
330 |
331 | http://www.apache.org/licenses/LICENSE-2.0
332 |
333 | Unless required by applicable law or agreed to in writing, software
334 | distributed under the License is distributed on an "AS IS" BASIS,
335 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
336 | See the License for the specific language governing permissions and
337 | limitations under the License.
338 |
--------------------------------------------------------------------------------