• This repository has been archived on 13/Jun/2019
  • Stars
    star
    449
  • Rank 97,328 (Top 2 %)
  • Language
    Java
  • License
    Apache License 2.0
  • Created over 10 years ago
  • Updated almost 8 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Android library listening network connection state and change of the WiFi signal strength with event bus

NetworkEvents

Travis CI Android Arsenal Maven Central

Android library listening network connection state and change of the WiFi signal strength with event bus.

It works with any implementation of the Event Bus. In this repository you can find samples with Otto and GreenRobot's bus.

min sdk version = 9

JavaDoc is available at: http://pwittchen.github.io/NetworkEvents

This project is deprecated!

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:

Contents

Overview

Library is able to detect ConnectivityStatus when it changes.

public enum ConnectivityStatus {
  UNKNOWN("unknown"),
  WIFI_CONNECTED("connected to WiFi"),
  WIFI_CONNECTED_HAS_INTERNET("connected to WiFi (Internet available)"),
  WIFI_CONNECTED_HAS_NO_INTERNET("connected to WiFi (Internet not available)"),
  MOBILE_CONNECTED("connected to mobile network"),
  OFFLINE("offline");
  ...
}    

In addition, it is able to detect situation when strength of the Wifi signal was changed with WifiSignalStrengthChanged event, when we enable WiFi scanning.

Library is able to detect MobileNetworkType when ConnectivityStatus changes to MOBILE_CONNECTED.

public enum MobileNetworkType {
  UNKNOWN("unknown"),
  LTE("LTE"),
  HSPAP("HSPAP"),
  EDGE("EDGE"),
  GPRS("GPRS");
  ...
}    

Usage

Appropriate permissions are already set in AndroidManifest.xml file for the library inside the <manifest> tag. They don't need to be set inside the specific application, which uses library.

Initialize objects

In your activity add BusWrapper field, which wraps your Event Bus. You can use Otto as in this sample and then create NetworkEvents field.

private BusWrapper busWrapper;
private NetworkEvents networkEvents;

Create implementation of BusWrapper. You can use any event bus here. E.g. GreenRobot's Event Bus. In this example, we are wrapping Otto Event bus.

private BusWrapper getOttoBusWrapper(final Bus bus) {
  return new BusWrapper() {
    @Override public void register(Object object) {
      bus.register(object);
    }

    @Override public void unregister(Object object) {
      bus.unregister(object);
    }

    @Override public void post(Object event) {
      bus.post(event);
    }
  };
}

Initialize objects in onCreate(Bundle savedInstanceState) method.

@Override protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  busWrapper = getOttoBusWrapper(new Bus());
  networkEvents = new NetworkEvents(context, busWrapper);
}

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

NetworkEvents Customization

Custom logger

By default library logs messages about changed connectivity or WiFi signal strength to LogCat. We can create custom logger implementation in the following way:

networkEvents = new NetworkEvents(context, busWrapper, new Logger() {
  @Override public void log(String message) {
    // log your message here
  }
});

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.

enabling WiFi scan

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:

networkEvents = new NetworkEvents(context, busWrapper)
  .enableWifiScan();
enabling Internet connection check

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. 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.

You can enable internet check as follows:

networkEvents = new NetworkEvents(context, busWrapper)
  .enableInternetCheck();
customizing ping parameters

You can customize ping parameters used to check Internet connectivity. You can set your own host, port and ping timeout in milliseconds as follows:

networkEvents = new NetworkEvents(context, busWrapper)
  .setPingParameters("www.anyhostyouwant.com", 80, 30)

In the example presented above, library will ping www.anyhostyouwant.com on port 80 with timeout equal to 30 milliseconds.

Register and unregister objects

We have to register and unregister objects in Activity Lifecycle.

In case of different Event Buses, we have to do it differently.

Otto Bus

Register BusWrapper and NetworkEvents in onResume() method and unregister them in onPause() method.

@Override protected void onResume() {
  super.onResume();
  busWrapper.register(this);
  networkEvents.register();
}

@Override protected void onPause() {
  super.onPause();
  busWrapper.unregister(this);
  networkEvents.unregister();
}

GreenRobot's Bus

Register BusWrapper and NetworkEvents in onStart() method and unregister them in onStop() method.

@Override protected void onStart() {
  super.onStart();
  busWrapper.register(this);
  networkEvents.register();
}

@Override protected void onStop() {
  busWrapper.unregister(this);
  networkEvents.unregister();
  super.onStop();
}

Subscribe for the events

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.

@Subscribe public void onEvent(ConnectivityChanged event) {
  // get connectivity status from event.getConnectivityStatus()
  // or mobile network type via event.getMobileNetworkType()
  // and do whatever you want
}

@Subscribe public void onEvent(WifiSignalStrengthChanged event) {
  // do whatever you want - e.g. read fresh list of access points
  // via event.getWifiScanResults() method
}

NetworkHelper

Library has additional class called NetworkHelper with static method, which can be used for determining if device is connected to WiFi or mobile network:

NetworkHelper.isConnectedToWiFiOrMobileNetwork(context)

It returns true if device is connected to one of mentioned networks and false if not.

Examples

  • Look at MainActivity in application located in example directory to see how this library works with Otto Event Bus.
  • Example presenting how to use this library with GreenRobot's Event Bus is presented in example-greenrobot-bus directory

Download

You can depend on the library through Maven:

<dependency>
  <groupId>com.github.pwittchen</groupId>
  <artifactId>networkevents</artifactId>
  <version>2.1.6</version>
</dependency>

or through Gradle:

dependencies {
  compile 'com.github.pwittchen:networkevents:2.1.6'
}

Remember to add dependency to the Event Bus, which you are using.

In case of Otto, add the following dependency through Maven:

<dependency>
  <groupId>com.squareup</groupId>
  <artifactId>otto</artifactId>
  <version>1.3.8</version>
</dependency>

or through Gradle:

dependencies {
  compile 'com.squareup:otto:1.3.8'
}

You can also use GreenRobot's Event Bus or any Event Bus you want.

Tests

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:

./gradlew connectedCheck

Test coverage report can be generated with the following command:

./gradlew createDebugCoverageReport

In order to generate report, emulator or Android device needs to be connected to the computer. Report will be generated in the network-events-library/build/outputs/reports/coverage/debug/ directory.

Code style

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

Who is using this library?

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

License

Copyright 2015 Piotr Wittchen

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

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

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

More Repositories

1

ReactiveNetwork

Android library listening network connection state and Internet connectivity with RxJava Observables
Java
2,527
star
2

spotify-cli-linux

๐ŸŽถ A command line interface to Spotify on Linux
Python
637
star
3

swipe

๐Ÿ‘‰ detects swipe events on Android
Java
328
star
4

RxBiometric

โ˜๏ธ RxJava and RxKotlin bindings for Biometric Prompt (Fingerprint Scanner) on Android
Kotlin
301
star
5

prefser

Wrapper for Android SharedPreferences with object serialization and RxJava Observables
Java
228
star
6

WeatherIconView

Weather Icon View for Android applications
Java
204
star
7

ReactiveWiFi

Android library listening available WiFi Access Points and related information with RxJava Observables
Java
189
star
8

InfiniteScroll

Infinite Scroll (Endless Scrolling) for RecyclerView in Android
Java
189
star
9

ReactiveBeacons

Android library scanning BLE beacons nearby with RxJava
Java
167
star
10

ReactiveSensors

Android library monitoring device hardware sensors with RxJava
Java
166
star
11

learning-linux

learning Linux (Unix) and collecting resources about it
99
star
12

kirai

String formatting library for Java, Android, Web and Unix Terminal
Java
71
star
13

interview-questions

interview questions for the software developer role and related resources
69
star
14

RxBattery

monitors battery state of the Android device
Kotlin
63
star
15

tmux-plugin-spotify

tmux plugin displaying currently played song on Spotify (linux only)
Shell
53
star
16

neurosky-android-sdk

Android SDK for the NeuroSky MindWave Mobile Brainwave Sensing Headset
Java
47
star
17

EEGReader

EEG Reader is an Android mobile application, which reads EEG signal from NeuroSky mobile device connected to smartphone via Bluetooth.
Java
39
star
18

android-quality-starter

setup CheckStyle, FindBugs, PMD and Lint for your Android project easily
Shell
29
star
19

ydocker

[unofficial PoC] get, build, initialize and run SAP Hybris Commerce Suite inside Docker container
Shell
29
star
20

ReactiveBus

๐Ÿš Reactive Event Bus for JVM (1.7+) and Android apps built with RxJava 2
Java
17
star
21

android-looper-sample

Exemplary Android app showing usage of Handler and Looper
Java
15
star
22

SearchTwitter

Android app, which allows to search tweets as user types and scroll them infinitely (Contentful Android Task)
Java
15
star
23

learn-python-the-hard-way

Set of programs written during learning basics of Python and related resources ๐Ÿ
Python
13
star
24

dockerfiles-java

various docker images with java
Dockerfile
11
star
25

dotfiles

my dotfiles
Shell
10
star
26

dockerw

docker wrapper bash script template
Shell
10
star
27

android-resource-converter

Scripts converting Android *.xml resources with translations to *.csv file and backwards
Python
9
star
28

ReactiveAirplaneMode

โœˆ๏ธ Android library listening airplane mode with RxJava Observables
Java
8
star
29

money-transfer-api

HTTP server with REST API for money transfer between bank accounts (Revolut Backend Task)
Java
8
star
30

pkup

semi-automated generating of PKUP report
Python
6
star
31

airly-statusbar

bash script for reading AQI from the airly.eu sensors for BitBar (macOS) and Argos (Linux + Gnome) statusbar
Shell
6
star
32

learning-csharp

Set of simple programs written during learning basics of C# language
C#
4
star
33

fix-skype-icon

โ˜Ž๏ธ shell script to fix the Skype icon in Ubuntu
Shell
4
star
34

tmux-plugin-ip

tmux plugin showing IP number
Shell
4
star
35

voucher-storage-service

microservice developed during "Kyma meets CCV2 Hackathon"
Kotlin
4
star
36

reactive-client-server

An example of reactive client and server apps written for "Hack Your Career" presentation about Reactive Programming at Silesian University of Technology
Java
4
star
37

touch

Android library, which allows to monitor raw touch events on the screen of the device with RxJava
Java
3
star
38

wittchen.io

a source code of my personal website and blog
HTML
3
star
39

learning-cobol

Repository created to learn basics of COBOL language and feel some vintage breeze
COBOL
3
star
40

ydownloader

shell script for downloading SAP Hybris Commerce Suite from Artifactory
Shell
3
star
41

tmux-auto-pane

a tiny tool for creating pre-defined tile layouts in tmux on linux with xdotool
Shell
3
star
42

learning-R

Repository created in order to learn basics of R language
R
2
star
43

serverless-lambda-playground

Playing around with serverless solutions, lambdas, cloud functions, etc.
Java
2
star
44

noti.py

simple script to show system notifications on Linux
Python
2
star
45

git-branch-comparator

Checks if development branch has all changes from master branch in Git repository
Python
2
star
46

HriseyPlayground

Playing with Hrisey to remove boilerplate code from Android projects
Java
2
star
47

java-flow-experiments

Experimenting with Reactive Streams in Java 8 and Java 9. This repository is prepared for my talk "Get ready for java.util.concurrent.Flow!" at JDD 2017 Conference in Krakรณw, Poland
Java
2
star
48

wallpapers

wallpapers I use on my desktop
1
star
49

learning-go

learning basics of go language
Go
1
star
50

craplog

verifies whether your git log is a crap or not
Python
1
star
51

nyan-cat-loader

Nyan cat loader made just for fun in HTML5, CSS3 and JavaScript.
CSS
1
star
52

learning-asm-x64-linux

Repository created in order to learn basics of Assembly x64 for Linux
Assembly
1
star
53

tmux-plugin-uptime

tmux plugin showing computer uptime
Shell
1
star
54

java-playground

a repo created for testing and learning different features of java and jvm libraries
Java
1
star
55

cv

my cv/resume as a code in LaTeX
TeX
1
star
56

tmux-plugin-ram

tmux plugin showing RAM usage
Shell
1
star
57

tmux-plugin-battery

tmux plugin showing battery level
Shell
1
star
58

github-actions-playground

a repo for testing GitHub Actions
1
star
59

HelloAndroidKotlin

Hello World Android app written in Kotlin
Kotlin
1
star
60

learning-docker

learning basics of Docker
Makefile
1
star
61

yaas-java-sdk

YaaS (Hybris as a Service) Java SDK
Java
1
star
62

Ant-algorithm

Implementation of the ant algorithm for AI laboratory at my univeristy.
Pascal
1
star
63

kotlin-playground

Repository created in order to learn basics of Kotlin language
Kotlin
1
star