11 |
12 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: android
2 | android:
3 | components:
4 | # Uncomment the lines below if you want to
5 | # use the latest revision of Android SDK Tools
6 | - platform-tools
7 | - tools
8 |
9 | # The BuildTools version used by your project
10 | - build-tools-23.0.2
11 |
12 | # The SDK version used to compile your project
13 | - android-23
14 |
15 | # Additional components
16 | - extra-google-m2repository
17 | - extra-android-m2repository
18 |
19 | # Specify at least one system image,
20 | # if you need to run emulator(s) during your tests
21 | - sys-img-armeabi-v7a-android-23
22 |
--------------------------------------------------------------------------------
/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 | Android Host Monitor
2 | ====================
3 |
4 | ## This library has been discontinued! I strongly recommend using https://github.com/pwittchen/ReactiveNetwork instead
5 |
6 | [](http://android-arsenal.com/details/1/2626) [](https://travis-ci.org/gotev/android-host-monitor) [  ](https://bintray.com/gotev/maven/android-host-monitor/_latestVersion) [](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=alexgotev%40gmail%2ecom&lc=US&item_name=Android%20Upload%20Service&item_number=AndroidHostMonitor¤cy_code=EUR&bn=PP%2dDonationsBF%3abtn_donate_SM%2egif%3aNonHosted)
7 |
8 | Easily monitor device network state and remote hosts reachability on Android.
9 |
10 | ## Purpose
11 | In today's massively interconnected world, it's a common thing for an App to communicate with remote servers to provide contents and functionalities to the end user, so it's a good thing to check if the app can "talk" with the needed servers before doing any other network operation. Often the app has to do something based on the reachability status of a particular server or handle transitions between networks. This kind of checking can easily become a mess when we have to deal with continuous network switching (Mobile to WiFi, WiFi to Mobile, Airplane mode, no connection) and battery life! Android Host Monitor handles that for you and let you focus purely on your app's business logic.
12 |
13 | ## Setup
14 | #### Maven
15 |
16 | ```
17 |
18 | net.gotev
19 | hostmonitor
20 | 2.0
21 | aar
22 |
23 | ```
24 |
25 | #### Gradle
26 |
27 | ```
28 | dependencies {
29 | compile 'net.gotev:hostmonitor:2.0@aar'
30 | }
31 | ```
32 | and do a project sync. Check [JavaDocs](http://gotev.github.io/android-host-monitor/javadoc/) for a complete reference.
33 |
34 | ## Get started
35 | Configuring a remote host reachability check is as simple as:
36 | ```java
37 | new HostMonitorConfig(context)
38 | .setBroadcastAction(BuildConfig.APPLICATION_ID)
39 | .add("my.server.com", 80)
40 | .save();
41 | ```
42 | You can do that from wherever you have a `Context`. What you've done here is the following:
43 | * you've set the broadcast action used by the library to notify reachability changes. In this case you used the Gradle application ID, but you can use whatever string you want, as long as it's unique in your app.
44 | * you've added the monitoring of `my.server.com` on port `80`. The library will immediately perform a reachability check and notify you of the status. Whenever the device connectivity status changes (e.g. from WiFi to 3G, from 3G to Airplane, from no connection to 3G, ...) the library will automatically perform a reachability check in the background and will notify you only if the status has been changed from the last time you received a notification.
45 |
46 | When you call `save()` the settings are persisted and immediately applied.
47 |
48 | Settings survives to application restarts and android restarts, so until you want to change the host monitor configuration, you can simply start the reachability check when your app starts by invoking:
49 | ```java
50 | new HostMonitorConfig(context).save();
51 | ```
52 |
53 | The library can also automatically perform scheduled periodic reachability checks, so for example if you want to monitor your server every 15 minutes, all you have to do is:
54 | ```java
55 | new HostMonitorConfig(context).setCheckIntervalInMinutes(15).save();
56 | ```
57 | Bear in mind that more frequent reachability checks drains your battery faster!
58 |
59 | You can also set other things such as socket connection timeout and maximum connection attempts before notifying failure. Check [JavaDocs](http://gotev.github.io/android-host-monitor/javadoc/).
60 |
61 | #### Unmonitor a host and port
62 | ```java
63 | new HostMonitorConfig(context).remove("my.server.com", 80).save();
64 | ```
65 |
66 | #### Remove all the monitored hosts
67 | ```java
68 | new HostMonitorConfig(context).removeAll().save();
69 | ```
70 | When there are no hosts left to be monitored, the library automatically shuts down the connectivity monitoring and clears all the scheduled checks.
71 |
72 | #### Reset configuration to factory defaults
73 | If you want to reset the persisted configuration, just invoke:
74 | ```java
75 | HostMonitorConfig.reset(context);
76 | ```
77 | This will reset the configuration to factory defaults and will stop any active and scheduled network check.
78 |
79 | #### Receive reachability status changes
80 | To listen for the status, subclass `HostMonitorBroadcastReceiver`.
81 | If you want to monitor host reachability globally in your app, all you have to do is create a new class (called `HostReachabilityReceiver` in this example):
82 |
83 | ```java
84 | public class HostReachabilityReceiver extends HostMonitorBroadcastReceiver {
85 | @Override
86 | public void onHostStatusChanged(HostStatus status) {
87 | Log.i("HostReachability", status.toString());
88 | }
89 | }
90 | ```
91 |
92 | and register it as a Broadcast receiver in your manifest:
93 |
94 | ```xml
95 |
99 |
100 |
101 |
102 |
103 | ```
104 |
105 | `com.yourcompany.yourapp.reachability` must be the same string you set as broadcast action in the configuration, otherwise you will not receive reachability events.
106 |
107 | You can receive status updates also in your `Activity` or `Service`. Here there is an example inside an `Activity`:
108 |
109 | ```java
110 | public class YourActivity extends Activity {
111 |
112 | private final HostMonitorBroadcastReceiver receiver =
113 | new HostMonitorBroadcastReceiver() {
114 | @Override
115 | public void onHostStatusChanged(HostStatus status) {
116 | Log.i("HostMonitor", status.toString());
117 | }
118 | };
119 |
120 | @Override
121 | protected void onResume() {
122 | super.onResume();
123 | receiver.register(this);
124 | }
125 |
126 | @Override
127 | protected void onPause() {
128 | super.onPause();
129 | receiver.unregister(this);
130 | }
131 | }
132 | ```
133 | A partial wake lock is automatically held for the entire execution of the `onHostStatusChanged` method and is released as soon as the method returns.
134 |
135 |
136 | ## Logging
137 | By default the library logging is disabled. You can enable debug log by invoking:
138 | ```java
139 | Logger.setLogLevel(LogLevel.DEBUG);
140 | ```
141 |
142 | The library logger uses `android.util.Log`, but you can override that by providing your own logger implementation like this:
143 | ```java
144 | Logger.setLoggerDelegate(new Logger.LoggerDelegate() {
145 | @Override
146 | public void error(String tag, String message) {
147 | //your own implementation here
148 | }
149 |
150 | @Override
151 | public void error(String tag, String message, Throwable exception) {
152 | //your own implementation here
153 | }
154 |
155 | @Override
156 | public void debug(String tag, String message) {
157 | //your own implementation here
158 | }
159 |
160 | @Override
161 | public void info(String tag, String message) {
162 | //your own implementation here
163 | }
164 | });
165 | ```
166 |
167 | ## Issues
168 | When you post a new issue regarding a possible bug in the library, make sure to add as many details as possible to be able to reproduce and solve the error you encountered in less time. Thank you :)
169 |
170 | ## Contribute
171 | * Do you have a new feature in mind?
172 | * Do you know how to improve existing docs or code?
173 | * Have you found a bug?
174 |
175 | Contributions are welcome and encouraged! Just fork the project and then send a pull request. Be ready to discuss your code and design decisions :)
176 |
177 | ## Do you like the project?
178 | Put a star, spread the word and if you want to offer me a free beer, [](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=alexgotev%40gmail%2ecom&lc=US&item_name=Android%20Upload%20Service&item_number=AndroidHostMonitor¤cy_code=EUR&bn=PP%2dDonationsBF%3abtn_donate_SM%2egif%3aNonHosted)
179 |
180 | ## License
181 |
182 | Copyright (C) 2015-2016 Aleksandar Gotev
183 |
184 | Licensed under the Apache License, Version 2.0 (the "License");
185 | you may not use this file except in compliance with the License.
186 | You may obtain a copy of the License at
187 |
188 | http://www.apache.org/licenses/LICENSE-2.0
189 |
190 | Unless required by applicable law or agreed to in writing, software
191 | distributed under the License is distributed on an "AS IS" BASIS,
192 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
193 | See the License for the specific language governing permissions and
194 | limitations under the License.
195 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | mavenCentral()
7 | }
8 | dependencies {
9 | classpath 'com.android.tools.build:gradle:1.5.0'
10 | classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3'
11 | classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.4'
12 |
13 | // NOTE: Do not place your application dependencies here; they belong
14 | // in the individual module build.gradle files
15 | }
16 | }
17 |
18 | allprojects {
19 | repositories {
20 | jcenter()
21 | mavenCentral()
22 | }
23 | }
24 |
25 | task clean(type: Delete) {
26 | delete rootProject.buildDir
27 | }
28 |
--------------------------------------------------------------------------------
/generate-javadoc.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash -e
2 | ./gradlew clean javadoc
3 | rm -rf ../javadoc
4 | mv hostmonitor/build/docs/javadoc/ ../
5 | git checkout gh-pages
6 | rm -rf javadoc
7 | mv ../javadoc .
8 | cd javadoc
9 | git add . --force
10 | git commit -m "updated javadocs"
11 | git push
12 | cd ..
13 | git checkout master
14 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
19 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gotev/android-host-monitor/fe484dcc387f0f8317b3e7af412c694adf43cc40/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sun Oct 11 14:28:58 CEST 2015
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.4-all.zip
7 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/hostmonitor/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'com.github.dcendents.android-maven'
3 | apply plugin: 'com.jfrog.bintray'
4 |
5 | def siteUrl = 'https://github.com/gotev/android-host-monitor/'
6 | def gitUrl = 'https://github.com/gotev/android-host-monitor.git'
7 | def projectName = "android-host-monitor"
8 | def projectDesc = "Easily monitor device network state and remote hosts reachability on Android"
9 | def projectGroup = "net.gotev"
10 | group = projectGroup
11 | version = "2.0"
12 |
13 | android {
14 | compileSdkVersion 23
15 | buildToolsVersion "23.0.2"
16 |
17 | defaultConfig {
18 | minSdkVersion 14
19 | targetSdkVersion 23
20 | versionCode 2
21 | versionName version
22 | }
23 | buildTypes {
24 | release {
25 | minifyEnabled false
26 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
27 | }
28 | }
29 | }
30 |
31 | dependencies {
32 | compile 'com.google.code.gson:gson:2.5'
33 | }
34 |
35 | // add the following information to the file: local.properties situated in the parent directory of
36 | // where this file is:
37 | //
38 | // bintray.user=alexbbb
39 | // bintray.apikey=api key got from the bintray profile
40 | //
41 | // be sure to add local.properties to the .gitignore!
42 |
43 | Properties properties = new Properties()
44 | if (project.rootProject.file("local.properties").exists()) {
45 | properties.load(project.rootProject.file('local.properties').newDataInputStream())
46 | }
47 |
48 | install {
49 | repositories.mavenInstaller {
50 | pom.project {
51 | name projectName
52 | description projectDesc
53 | packaging 'aar'
54 | groupId projectGroup
55 | version version
56 | url siteUrl
57 | licenses {
58 | license {
59 | name 'The Apache Software License, Version 2.0'
60 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
61 | }
62 | }
63 | developers {
64 | developer {
65 | id 'gotev'
66 | name 'Aleksandar Gotev'
67 | }
68 | }
69 | scm {
70 | connection gitUrl
71 | developerConnection gitUrl
72 | url siteUrl
73 |
74 | }
75 | }
76 | }
77 | }
78 |
79 | bintray {
80 | user = properties.getProperty("bintray.user")
81 | key = properties.getProperty("bintray.apikey")
82 | configurations = ['archives']
83 | pkg {
84 | repo = "maven"
85 | name = projectName
86 | desc = projectDesc
87 | websiteUrl = siteUrl
88 | vcsUrl = gitUrl
89 | issueTrackerUrl = siteUrl + "/issues/"
90 | licenses = ["Apache-2.0"]
91 | labels = ['android', 'host', 'monitor', 'library', 'background', 'reachability', 'port', 'check']
92 | publicDownloadNumbers = true
93 | publish = true
94 | }
95 | }
96 |
97 | task sourcesJar(type: Jar) {
98 | from android.sourceSets.main.java.srcDirs
99 | classifier = 'sources'
100 | }
101 |
102 | task javadoc(type: Javadoc) {
103 | title = "Android Host Monitor $project.version API"
104 | description "Generates Javadoc"
105 | source = android.sourceSets.main.java.srcDirs
106 | classpath += files(android.bootClasspath)
107 | exclude '**/BuildConfig.java', '**/R.java'
108 | options {
109 | windowTitle("Android Host Monitor $project.version Reference")
110 | locale = 'en_US'
111 | encoding = 'UTF-8'
112 | charSet = 'UTF-8'
113 | links("http://docs.oracle.com/javase/7/docs/api/");
114 | linksOffline("http://d.android.com/reference", "${android.sdkDirectory}/docs/reference");
115 | setMemberLevel(JavadocMemberLevel.PUBLIC)
116 | }
117 | }
118 |
119 | task javadocJar(type: Jar, dependsOn: javadoc) {
120 | classifier = 'javadoc'
121 | from javadoc.destinationDir
122 | }
123 |
124 | artifacts {
125 | archives javadocJar
126 | archives sourcesJar
127 | }
128 |
--------------------------------------------------------------------------------
/hostmonitor/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 /Users/alex/workspace/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 |
--------------------------------------------------------------------------------
/hostmonitor/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
12 |
16 |
17 |
18 |
19 |
20 |
21 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/hostmonitor/src/main/java/net/gotev/hostmonitor/ConnectionType.java:
--------------------------------------------------------------------------------
1 | package net.gotev.hostmonitor;
2 |
3 | /**
4 | * Enumeration of the connection types.
5 | * @author gotev (Aleksandar Gotev)
6 | */
7 | public enum ConnectionType {
8 | NONE,
9 | WIFI,
10 | MOBILE
11 | }
12 |
--------------------------------------------------------------------------------
/hostmonitor/src/main/java/net/gotev/hostmonitor/ConnectivityReceiver.java:
--------------------------------------------------------------------------------
1 | package net.gotev.hostmonitor;
2 |
3 | import android.content.BroadcastReceiver;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.os.PowerManager;
7 |
8 | /**
9 | * Monitors connectivity changes.
10 | * @author gotev (Aleksandar Gotev)
11 | */
12 | public class ConnectivityReceiver extends BroadcastReceiver {
13 |
14 | private static final String LOG_TAG = "HostMonitorCR";
15 |
16 | private static volatile PowerManager.WakeLock wakeLock;
17 |
18 | @Override
19 | public void onReceive(Context context, Intent intent) {
20 | Logger.debug(LOG_TAG, "onReceive");
21 |
22 | manageWakeLock(context);
23 |
24 | ConnectionType connectionType = HostMonitor.getCurrentConnectionType(context);
25 |
26 | Logger.debug(LOG_TAG, (connectionType == ConnectionType.NONE) ?
27 | "connection unavailable" :
28 | "connection available via " + connectionType);
29 |
30 | HostMonitor.start(context, connectionType);
31 | }
32 |
33 | private synchronized void manageWakeLock(Context context) {
34 | if (wakeLock != null && wakeLock.isHeld()) {
35 | wakeLock.release();
36 | }
37 |
38 | PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
39 | wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, LOG_TAG);
40 | wakeLock.setReferenceCounted(false);
41 | wakeLock.acquire(10 * 1000);
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/hostmonitor/src/main/java/net/gotev/hostmonitor/DefaultLoggerDelegate.java:
--------------------------------------------------------------------------------
1 | package net.gotev.hostmonitor;
2 |
3 | import android.util.Log;
4 |
5 | /**
6 | * Default logger delegate implementation which logs in LogCat with {@link Log}.
7 | * @author gotev (Aleksandar Gotev)
8 | */
9 | public class DefaultLoggerDelegate implements Logger.LoggerDelegate {
10 | @Override
11 | public void error(String tag, String message) {
12 | Log.e(tag, message);
13 | }
14 |
15 | @Override
16 | public void error(String tag, String message, Throwable exception) {
17 | Log.e(tag, message, exception);
18 | }
19 |
20 | @Override
21 | public void debug(String tag, String message) {
22 | Log.d(tag, message);
23 | }
24 |
25 | @Override
26 | public void info(String tag, String message) {
27 | Log.i(tag, message);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/hostmonitor/src/main/java/net/gotev/hostmonitor/Host.java:
--------------------------------------------------------------------------------
1 | package net.gotev.hostmonitor;
2 |
3 | import java.net.InetSocketAddress;
4 |
5 | /**
6 | * Represents a host to monitor.
7 | * @author gotev (Aleksandar Gotev)
8 | */
9 | class Host {
10 | private final String host;
11 | private final int port;
12 |
13 | public Host(String host, int port) {
14 | this.host = host;
15 | this.port = port;
16 | }
17 |
18 | public String getHost() {
19 | return host;
20 | }
21 |
22 | public int getPort() {
23 | return port;
24 | }
25 |
26 | public InetSocketAddress resolve() {
27 | return new InetSocketAddress(host, port);
28 | }
29 |
30 | @Override
31 | public boolean equals(Object o) {
32 | if (this == o) return true;
33 | if (o == null || getClass() != o.getClass()) return false;
34 |
35 | Host host1 = (Host) o;
36 |
37 | return port == host1.port && host.equals(host1.host);
38 | }
39 |
40 | @Override
41 | public int hashCode() {
42 | int result = host.hashCode();
43 | result = 31 * result + port;
44 | return result;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/hostmonitor/src/main/java/net/gotev/hostmonitor/HostMonitor.java:
--------------------------------------------------------------------------------
1 | package net.gotev.hostmonitor;
2 |
3 | import android.app.IntentService;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.net.ConnectivityManager;
7 | import android.net.NetworkInfo;
8 | import android.os.PowerManager;
9 |
10 | import java.net.Socket;
11 |
12 | /**
13 | * Service which performs reachability checks of the configured hosts and ports.
14 | * @author gotev (Aleksandar Gotev)
15 | */
16 | public class HostMonitor extends IntentService {
17 |
18 | private static final String LOG_TAG = HostMonitor.class.getSimpleName();
19 | private static final String ACTION_CHECK = "net.gotev.hostmonitor.check";
20 |
21 | private static final String PARAM_CONNECTION_TYPE = "net.gotev.hostmonitor.connection_type";
22 |
23 | /**
24 | * Name of the parameter passed in the broadcast intent.
25 | */
26 | public static final String PARAM_STATUS = "HostStatus";
27 |
28 | public HostMonitor() {
29 | super(LOG_TAG);
30 | }
31 |
32 | /**
33 | * Returns the {@link Intent} to start the service reachability check.
34 | * @param context application context
35 | * @return intent used to launch the service
36 | */
37 | static Intent getCheckIntent(Context context) {
38 | Intent intent = new Intent(context, HostMonitor.class);
39 | intent.setAction(ACTION_CHECK);
40 | return intent;
41 | }
42 |
43 | /**
44 | * Starts the host monitor check
45 | * @param context application context
46 | */
47 | static void start(Context context) {
48 | context.startService(getCheckIntent(context));
49 | }
50 |
51 | /**
52 | * Starts the host monitor check.
53 | * @param context application context
54 | * @param connectionType current connection type
55 | */
56 | static void start(Context context, ConnectionType connectionType) {
57 | Intent intent = new Intent(context, HostMonitor.class);
58 | intent.setAction(ACTION_CHECK);
59 | intent.putExtra(PARAM_CONNECTION_TYPE, connectionType.ordinal());
60 | context.startService(intent);
61 | }
62 |
63 | /**
64 | * Stops the host monitor check.
65 | * @param context application context
66 | */
67 | public static void stop(Context context) {
68 | context.stopService(new Intent(context, HostMonitor.class));
69 | }
70 |
71 | @Override
72 | protected void onHandleIntent(Intent intent) {
73 | if (intent == null || !ACTION_CHECK.equals(intent.getAction())) return;
74 |
75 | PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
76 | PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
77 | getClass().getSimpleName());
78 |
79 | wakeLock.acquire();
80 |
81 | HostMonitorConfig config = new HostMonitorConfig(this);
82 |
83 | if (config.getHostsMap().isEmpty()) {
84 | Logger.debug(LOG_TAG, "No hosts to check at this moment");
85 |
86 | } else {
87 | ConnectionType connectionType = getConnectionType(intent);
88 |
89 | if (connectionType == ConnectionType.NONE) {
90 | notifyThatAllTheHostsAreUnreachable(connectionType, config);
91 | } else {
92 | checkReachability(connectionType, config);
93 | }
94 | }
95 |
96 | wakeLock.release();
97 | }
98 |
99 | private void notifyThatAllTheHostsAreUnreachable(ConnectionType connectionType,
100 | HostMonitorConfig config) {
101 | Logger.debug(LOG_TAG, "No active connection. Notifying that all the hosts are unreachable");
102 |
103 | for (Host host : config.getHostsMap().keySet()) {
104 | Status previousStatus = config.getHostsMap().get(host);
105 | Status newStatus = new Status(false, connectionType);
106 |
107 | if (!newStatus.equals(previousStatus)) {
108 | Logger.debug(LOG_TAG, "Host " + host.getHost() + " is currently unreachable on port "
109 | + host.getPort());
110 |
111 | config.getHostsMap().put(host, newStatus);
112 | notifyStatus(config.getBroadcastAction(), host, previousStatus, newStatus);
113 | }
114 | }
115 |
116 | config.saveHostsMap();
117 | }
118 |
119 | private void checkReachability(ConnectionType connectionType, HostMonitorConfig config) {
120 | Logger.debug(LOG_TAG, "Starting reachability check");
121 |
122 | for (Host host : config.getHostsMap().keySet()) {
123 | Status previousStatus = config.getHostsMap().get(host);
124 | boolean currentReachable = isReachable(host, config.getSocketTimeout(), config.getMaxAttempts());
125 | Status newStatus = new Status(currentReachable, connectionType);
126 |
127 | if (!newStatus.equals(previousStatus)) {
128 | Logger.debug(LOG_TAG, "Host " + host.getHost() + " is currently " +
129 | (currentReachable ? "reachable" : "unreachable") +
130 | " on port " + host.getPort() + " via " + connectionType);
131 |
132 | config.getHostsMap().put(host, newStatus);
133 | notifyStatus(config.getBroadcastAction(), host, previousStatus, newStatus);
134 | }
135 | }
136 |
137 | config.saveHostsMap();
138 | Logger.debug(LOG_TAG, "Reachability check finished!");
139 | }
140 |
141 | private ConnectionType getConnectionType(Intent intent) {
142 | int connTypeInt = intent.getIntExtra(PARAM_CONNECTION_TYPE, -1);
143 |
144 | ConnectionType type;
145 |
146 | if (connTypeInt < 0) {
147 | type = getCurrentConnectionType(this);
148 | } else {
149 | type = ConnectionType.values()[connTypeInt];
150 | }
151 |
152 | return type;
153 | }
154 |
155 | static ConnectionType getCurrentConnectionType(Context context) {
156 | ConnectivityManager connectivityManager =
157 | (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
158 |
159 | NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
160 |
161 | if (networkInfo == null || !networkInfo.isConnected()) {
162 | return ConnectionType.NONE;
163 | }
164 |
165 | int type = networkInfo.getType();
166 |
167 | if (type == ConnectivityManager.TYPE_MOBILE) return ConnectionType.MOBILE;
168 | if (type == ConnectivityManager.TYPE_WIFI) return ConnectionType.WIFI;
169 |
170 | Logger.error(LOG_TAG, "Unsupported connection type: " + type + ". Returning NONE");
171 | return ConnectionType.NONE;
172 | }
173 |
174 | private boolean isReachable(Host host, int connectTimeout, int maxAttempts) {
175 | int attempts = 0;
176 | boolean reachable = false;
177 |
178 | while (attempts < maxAttempts) {
179 | reachable = isReachable(host, connectTimeout);
180 | if (reachable) break;
181 | attempts++;
182 | }
183 |
184 | return reachable;
185 | }
186 |
187 | private boolean isReachable(Host host, int connectTimeout) {
188 | boolean reachable;
189 | Socket socket = null;
190 |
191 | try {
192 | socket = new Socket();
193 | socket.connect(host.resolve(), connectTimeout);
194 | reachable = true;
195 |
196 | } catch (Exception exc) {
197 | reachable = false;
198 |
199 | } finally {
200 | if (socket != null) {
201 | try {
202 | socket.close();
203 | } catch (Exception exc) {
204 | Logger.debug(LOG_TAG, "Error while closing socket.");
205 | }
206 | }
207 | }
208 |
209 | return reachable;
210 | }
211 |
212 | private void notifyStatus(String broadcastAction, Host host,
213 | Status previousStatus, Status currentStatus) {
214 | HostStatus status = new HostStatus()
215 | .setHost(host.getHost())
216 | .setPort(host.getPort())
217 | .setPreviousReachable(previousStatus.isReachable())
218 | .setPreviousConnectionType(previousStatus.getConnectionType())
219 | .setReachable(currentStatus.isReachable())
220 | .setConnectionType(currentStatus.getConnectionType());
221 |
222 | Logger.debug(LOG_TAG, "Broadcast with action: " + broadcastAction +
223 | " and status: " + status);
224 | Intent broadcastStatus = new Intent(broadcastAction);
225 | broadcastStatus.putExtra(PARAM_STATUS, status);
226 |
227 | sendBroadcast(broadcastStatus);
228 | }
229 | }
230 |
--------------------------------------------------------------------------------
/hostmonitor/src/main/java/net/gotev/hostmonitor/HostMonitorBroadcastReceiver.java:
--------------------------------------------------------------------------------
1 | package net.gotev.hostmonitor;
2 |
3 | import android.content.BroadcastReceiver;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.content.IntentFilter;
7 | import android.os.PowerManager;
8 |
9 | /**
10 | * Reference implementation of the HostMonitor broadcast receiver.
11 | * @author gotev (Aleksandar Gotev)
12 | */
13 | public class HostMonitorBroadcastReceiver extends BroadcastReceiver {
14 |
15 | @Override
16 | public void onReceive(Context context, Intent intent) {
17 | String action = new HostMonitorConfig(context).getBroadcastAction();
18 |
19 | if (intent == null || action == null || !intent.getAction().equals(action)) {
20 | return;
21 | }
22 |
23 | PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
24 | PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
25 | getClass().getSimpleName());
26 |
27 | wakeLock.acquire();
28 |
29 | HostStatus hostStatus = intent.getParcelableExtra(HostMonitor.PARAM_STATUS);
30 | onHostStatusChanged(hostStatus);
31 |
32 | wakeLock.release();
33 | }
34 |
35 | /**
36 | * Register this host monitor receiver.
37 | * If you use this receiver in an {@link android.app.Activity}, you have to call this method inside
38 | * {@link android.app.Activity#onResume()}, after {@code super.onResume();}.
39 | * If you use it in a {@link android.app.Service}, you have to
40 | * call this method inside {@link android.app.Service#onCreate()}, after {@code super.onCreate();}.
41 | *
42 | * @param context context in which to register this receiver
43 | */
44 | public void register(final Context context) {
45 | final IntentFilter intentFilter = new IntentFilter();
46 | intentFilter.addAction(new HostMonitorConfig(context).getBroadcastAction());
47 | context.registerReceiver(this, intentFilter);
48 | }
49 |
50 | /**
51 | * Unregister this host monitor receiver.
52 | * If you use this receiver in an {@link android.app.Activity}, you have to call this method inside
53 | * {@link android.app.Activity#onPause()}, after {@code super.onPause();}.
54 | * If you use it in a {@link android.app.Service}, you have to
55 | * call this method inside {@link android.app.Service#onDestroy()}.
56 | *
57 | * @param context context in which to unregister this receiver
58 | */
59 | public void unregister(final Context context) {
60 | context.unregisterReceiver(this);
61 | }
62 |
63 | /**
64 | * Method called when there's a host status change.
65 | * Override this in subclasses to implement your own business logic.
66 | * A partial wake lock is automatically held for you when code is executed inside this method.
67 | * Once the execution ends, the wake lock gets released.
68 | * @param status new host status
69 | */
70 | public void onHostStatusChanged(HostStatus status) {
71 | Logger.info("HostMonitorBR", "host status changed: " + status);
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/hostmonitor/src/main/java/net/gotev/hostmonitor/HostMonitorConfig.java:
--------------------------------------------------------------------------------
1 | package net.gotev.hostmonitor;
2 |
3 | import android.app.AlarmManager;
4 | import android.app.PendingIntent;
5 | import android.content.Context;
6 | import android.content.SharedPreferences;
7 |
8 | import com.google.gson.Gson;
9 | import com.google.gson.GsonBuilder;
10 | import com.google.gson.reflect.TypeToken;
11 |
12 | import java.lang.reflect.Type;
13 | import java.util.HashMap;
14 | import java.util.Map;
15 |
16 | /**
17 | * Host Monitor configuration manager.
18 | * @author gotev (Aleksandar Gotev)
19 | */
20 | public class HostMonitorConfig {
21 |
22 | // shared preferences file name
23 | private static final String PREFS_FILE_NAME = "host_monitor_config";
24 |
25 | // shared preferences keys
26 | private static final String KEY_HOSTS = "hosts";
27 | private static final String KEY_BROADCAST_ACTION = "broadcastAction";
28 | private static final String KEY_SOCKET_TIMEOUT = "socketTimeout";
29 | private static final String KEY_CHECK_INTERVAL = "checkInterval";
30 | private static final String KEY_MAX_ATTEMPTS = "maxAttempts";
31 |
32 | // default values
33 | private static final String DEFAULT_BROADCAST_ACTION = "net.gotev.hostmonitor.status";
34 | private static final int DEFAULT_SOCKET_TIMEOUT = 2000; //in milliseconds
35 | private static final int DEFAULT_CHECK_INTERVAL = 0; //in milliseconds
36 | private static final int DEFAULT_MAX_ATTEMPTS = 3;
37 | private static final int UNDEFINED = -1;
38 | private static final int PERIODIC_CHECK_ID = 0;
39 |
40 | private final Context mContext;
41 | private SharedPreferences mSharedPreferences;
42 |
43 | private Map mHostsMap;
44 | private String mBroadcastAction;
45 | private int mSocketTimeout = UNDEFINED;
46 | private int mCheckInterval = UNDEFINED;
47 | private int mMaxAttempts = UNDEFINED;
48 |
49 | /**
50 | * Creates a new Host Monitor configuration instance
51 | * @param context application context
52 | */
53 | public HostMonitorConfig(Context context) {
54 | mContext = context.getApplicationContext();
55 | }
56 |
57 | private SharedPreferences getPrefs() {
58 | if (mSharedPreferences == null) {
59 | mSharedPreferences = mContext.getSharedPreferences(PREFS_FILE_NAME, Context.MODE_PRIVATE);
60 | }
61 |
62 | return mSharedPreferences;
63 | }
64 |
65 | Map getHostsMap() {
66 | if (mHostsMap == null) {
67 | String json = getPrefs().getString(KEY_HOSTS, "");
68 |
69 | if (json.isEmpty()) {
70 | mHostsMap = new HashMap<>();
71 | } else {
72 | Type typeOfMap = new TypeToken>(){}.getType();
73 | try {
74 | mHostsMap = new Gson().fromJson(json, typeOfMap);
75 | } catch (Exception exc) {
76 | Logger.error(getClass().getSimpleName(),
77 | "Error while deserializing hosts map: " + json
78 | + ". Ignoring values.", exc);
79 | mHostsMap = new HashMap<>();
80 | }
81 | }
82 | }
83 |
84 | return mHostsMap;
85 | }
86 |
87 | /**
88 | * Set the broadcast action string to use when broadcasting host status changes
89 | * @param broadcastAction (e.g.: com.example.yourapp.hoststatus)
90 | * @return {@link HostMonitorConfig}
91 | */
92 | public HostMonitorConfig setBroadcastAction(String broadcastAction) {
93 | if (broadcastAction == null || broadcastAction.isEmpty())
94 | throw new IllegalArgumentException("Broadcast action MUST not be null or empty!");
95 |
96 | mBroadcastAction = broadcastAction;
97 | return this;
98 | }
99 |
100 | /**
101 | * Gets the broadcast action used for host status changes.
102 | * @return the configured broadcast action string
103 | */
104 | public String getBroadcastAction() {
105 | if (mBroadcastAction == null) {
106 | mBroadcastAction = getPrefs().getString(KEY_BROADCAST_ACTION, DEFAULT_BROADCAST_ACTION);
107 | }
108 |
109 | return mBroadcastAction;
110 | }
111 |
112 | /**
113 | * Adds a new host to be monitored. The change will be applied starting from the next
114 | * reachability scan.
115 | * @param host host IP address or FQDN
116 | * @param port TCP port to check
117 | * @return {@link HostMonitorConfig}
118 | */
119 | public HostMonitorConfig add(final String host, final int port) {
120 | Host newHost = new Host(host, port);
121 |
122 | if (getHostsMap().keySet().contains(newHost)) return this;
123 |
124 | mHostsMap.put(newHost, new Status());
125 |
126 | return this;
127 | }
128 |
129 | /**
130 | * Remove a monitored host. The change will be applied starting from the next
131 | * reachability scan.
132 | * @param host host address to check
133 | * @param port tcp port to check
134 | * @return {@link HostMonitorConfig}
135 | */
136 | public HostMonitorConfig remove(final String host, final int port) {
137 | Host toRemove = new Host(host, port);
138 |
139 | if (!getHostsMap().keySet().contains(toRemove)) return this;
140 |
141 | mHostsMap.remove(toRemove);
142 |
143 | return this;
144 | }
145 |
146 | /**
147 | * Remove all the monitored hosts.
148 | * @return {@link HostMonitorConfig}
149 | */
150 | public HostMonitorConfig removeAll() {
151 | if (mHostsMap != null) {
152 | mHostsMap.clear();
153 | }
154 |
155 | return this;
156 | }
157 |
158 | /**
159 | * Set socket connection timeout in seconds.
160 | * @param seconds maximum number of seconds to wait for a socket connection to be
161 | * established
162 | * @return {@link HostMonitorConfig}
163 | */
164 | public HostMonitorConfig setSocketTimeoutInSeconds(int seconds) {
165 | if (seconds < 1)
166 | throw new IllegalArgumentException("Specify at least one second timeout!");
167 |
168 | mSocketTimeout = seconds * 1000;
169 | return this;
170 | }
171 |
172 | /**
173 | * Set socket connection timeout in milliseconds.
174 | * @param millisecs maximum number of seconds to wait for a socket connection to be
175 | * established
176 | * @return {@link HostMonitorConfig}
177 | */
178 | public HostMonitorConfig setSocketTimeoutInMilliseconds(int millisecs) {
179 | if (millisecs < 1)
180 | throw new IllegalArgumentException("Specify at least one millisecond timeout!");
181 |
182 | mSocketTimeout = millisecs;
183 | return this;
184 | }
185 |
186 | /**
187 | * Get socket timeout in milliseconds. By default is 2000.
188 | * @return the configured socket timeout
189 | */
190 | public int getSocketTimeout() {
191 | if (mSocketTimeout <= 0) {
192 | mSocketTimeout = getPrefs().getInt(KEY_SOCKET_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
193 | }
194 |
195 | return mSocketTimeout;
196 | }
197 |
198 | /**
199 | * Set check interval in seconds.
200 | * 0 means that check interval is disabled (it's the default value).
201 | * @param seconds how often to check for hosts reachability
202 | * @return {@link HostMonitorConfig}
203 | */
204 | public HostMonitorConfig setCheckIntervalInSeconds(int seconds) {
205 | if (seconds < 0)
206 | throw new IllegalArgumentException("Specify a zero or positive check interval!");
207 |
208 | mCheckInterval = seconds * 1000;
209 | return this;
210 | }
211 |
212 | /**
213 | * Set check interval in minutes.
214 | * 0 means that check interval is disabled (it's the default value).
215 | * @param minutes how often to check for hosts reachability
216 | * @return {@link HostMonitorConfig}
217 | */
218 | public HostMonitorConfig setCheckIntervalInMinutes(int minutes) {
219 | if (minutes < 0)
220 | throw new IllegalArgumentException("Specify a zero or positive check interval!");
221 |
222 | mCheckInterval = minutes * 60 * 1000;
223 | return this;
224 | }
225 |
226 | /**
227 | * Get check interval in milliseconds. By default is zero, so no periodic check is
228 | * performed until you set it.
229 | * @return the configured check interval in milliseconds
230 | */
231 | public int getCheckInterval() {
232 | if (mCheckInterval <= 0) {
233 | mCheckInterval = getPrefs().getInt(KEY_CHECK_INTERVAL, DEFAULT_CHECK_INTERVAL);
234 | }
235 |
236 | return mCheckInterval;
237 | }
238 |
239 | /**
240 | * Sets the maximum number of socket connections to perform before notifying that the port
241 | * is unreachable.
242 | * @param maxAttempts maximum number of connections to try (must be at least 1)
243 | * @return {@link HostMonitorConfig}
244 | */
245 | public HostMonitorConfig setMaxAttempts(int maxAttempts) {
246 | if (maxAttempts < 1)
247 | throw new IllegalArgumentException("Set at least one attempt!");
248 |
249 | mMaxAttempts = maxAttempts;
250 | return this;
251 | }
252 |
253 | /**
254 | * Gets the maximum number of socket connections to perform before notifying that the port
255 | * is unreachable. Default value is 3.
256 | * @return number of attempts
257 | */
258 | public int getMaxAttempts() {
259 | if (mMaxAttempts <= 0) {
260 | mMaxAttempts = getPrefs().getInt(KEY_MAX_ATTEMPTS, DEFAULT_MAX_ATTEMPTS);
261 | }
262 |
263 | return mMaxAttempts;
264 | }
265 |
266 | void saveHostsMap() {
267 | Logger.debug(getClass().getSimpleName(), "saving hosts status map");
268 | Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
269 | getPrefs().edit().putString(KEY_HOSTS, gson.toJson(mHostsMap)).apply();
270 | }
271 |
272 | /**
273 | * Resets the currently persisted configuration.
274 | * Disables the connectivity receiver and cancels all scheduled periodic checks (if any).
275 | * @param context application context
276 | */
277 | public static void reset(Context context) {
278 | Logger.debug(HostMonitor.class.getSimpleName(), "reset configuration");
279 | context.getSharedPreferences(PREFS_FILE_NAME, Context.MODE_PRIVATE).edit().clear().apply();
280 |
281 | Util.setBroadcastReceiverEnabled(context, ConnectivityReceiver.class, false);
282 |
283 | Logger.debug(HostMonitor.class.getSimpleName(), "cancelling scheduled checks");
284 | AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
285 | alarmManager.cancel(getPeriodicCheckIntent(context));
286 | }
287 |
288 | /**
289 | * Saves and applies the configuration changes.
290 | * If there aren't configured hosts, it disables the {@link ConnectivityReceiver} and cancels
291 | * scheduled period checks. If there is at least one configured host, it enables the
292 | * {@link ConnectivityReceiver} and re-schedules periodic checks with new settings. If periodic
293 | * check interval is set to zero, host reachability checks will be triggered only when the
294 | * connectivity status of the device changes.
295 | */
296 | public void save() {
297 | Logger.debug(getClass().getSimpleName(), "saving configuration");
298 |
299 | SharedPreferences.Editor prefs = getPrefs().edit();
300 |
301 | if (mHostsMap != null && !mHostsMap.isEmpty()) {
302 | Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
303 | prefs.putString(KEY_HOSTS, gson.toJson(mHostsMap));
304 | }
305 |
306 | if (mBroadcastAction != null && !mBroadcastAction.isEmpty()) {
307 | prefs.putString(KEY_BROADCAST_ACTION, mBroadcastAction);
308 | }
309 |
310 | if (mSocketTimeout > 0) {
311 | prefs.putInt(KEY_SOCKET_TIMEOUT, mSocketTimeout);
312 | }
313 |
314 | if (mCheckInterval >= 0) {
315 | prefs.putInt(KEY_CHECK_INTERVAL, mCheckInterval);
316 | }
317 |
318 | if (mMaxAttempts > 0) {
319 | prefs.putInt(KEY_MAX_ATTEMPTS, mMaxAttempts);
320 | }
321 |
322 | prefs.apply();
323 |
324 | boolean thereIsAtLeastOneHost = !getHostsMap().isEmpty();
325 | Util.setBroadcastReceiverEnabled(mContext, ConnectivityReceiver.class, thereIsAtLeastOneHost);
326 |
327 | AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
328 | PendingIntent intent = getPeriodicCheckIntent(mContext);
329 |
330 | Logger.debug(HostMonitor.class.getSimpleName(), "cancelling scheduled checks");
331 | alarmManager.cancel(intent);
332 |
333 | if (thereIsAtLeastOneHost) {
334 | if (getCheckInterval() > 0) {
335 | Logger.debug(getClass().getSimpleName(), "scheduling periodic checks every " +
336 | (getCheckInterval() / 1000) + " seconds");
337 | alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
338 | System.currentTimeMillis() + getCheckInterval(),
339 | getCheckInterval(), intent);
340 | }
341 |
342 | Logger.debug(getClass().getSimpleName(), "triggering reachability check");
343 | HostMonitor.start(mContext);
344 | }
345 | }
346 |
347 | private static PendingIntent getPeriodicCheckIntent(Context context) {
348 | return PendingIntent.getBroadcast(context, PERIODIC_CHECK_ID,
349 | HostMonitor.getCheckIntent(context), 0);
350 | }
351 | }
352 |
--------------------------------------------------------------------------------
/hostmonitor/src/main/java/net/gotev/hostmonitor/HostStatus.java:
--------------------------------------------------------------------------------
1 | package net.gotev.hostmonitor;
2 |
3 | import android.os.Parcel;
4 | import android.os.Parcelable;
5 |
6 | import com.google.gson.Gson;
7 |
8 | /**
9 | * Contains the current and previous reachability status of a host and port.
10 | * @author gotev (Aleksandar Gotev)
11 | */
12 | public class HostStatus implements Parcelable {
13 |
14 | private String host;
15 | private int port;
16 | private boolean previousReachable;
17 | private boolean reachable;
18 | private ConnectionType previousConnectionType;
19 | private ConnectionType connectionType;
20 |
21 | public HostStatus() { }
22 |
23 | public String getHost() {
24 | return host;
25 | }
26 |
27 | public HostStatus setHost(String host) {
28 | this.host = host;
29 | return this;
30 | }
31 |
32 | public int getPort() {
33 | return port;
34 | }
35 |
36 | public HostStatus setPort(int port) {
37 | this.port = port;
38 | return this;
39 | }
40 |
41 | public boolean isPreviousReachable() {
42 | return previousReachable;
43 | }
44 |
45 | public HostStatus setPreviousReachable(boolean previousReachable) {
46 | this.previousReachable = previousReachable;
47 | return this;
48 | }
49 |
50 | public boolean isReachable() {
51 | return reachable;
52 | }
53 |
54 | public HostStatus setReachable(boolean reachable) {
55 | this.reachable = reachable;
56 | return this;
57 | }
58 |
59 | public ConnectionType getConnectionType() {
60 | return connectionType;
61 | }
62 |
63 | public HostStatus setConnectionType(ConnectionType connectionType) {
64 | this.connectionType = connectionType;
65 | return this;
66 | }
67 |
68 | public ConnectionType getPreviousConnectionType() {
69 | return previousConnectionType;
70 | }
71 |
72 | public HostStatus setPreviousConnectionType(ConnectionType connectionType) {
73 | this.previousConnectionType = connectionType;
74 | return this;
75 | }
76 |
77 | public boolean connectionTypeChanged() {
78 | return previousConnectionType != connectionType;
79 | }
80 |
81 | public boolean reachabilityChanged() {
82 | return previousReachable != reachable;
83 | }
84 |
85 | // This is used to regenerate the object.
86 | // All Parcelables must have a CREATOR that implements these two methods
87 | public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
88 | @Override
89 | public HostStatus createFromParcel(final Parcel in) {
90 | return new HostStatus(in);
91 | }
92 |
93 | @Override
94 | public HostStatus[] newArray(final int size) {
95 | return new HostStatus[size];
96 | }
97 | };
98 |
99 | @Override
100 | public int describeContents() {
101 | return 0;
102 | }
103 |
104 | @Override
105 | public void writeToParcel(Parcel dest, int flags) {
106 | dest.writeString(host);
107 | dest.writeInt(port);
108 | dest.writeInt(previousReachable ? 1 : 0);
109 | dest.writeInt(reachable ? 1 : 0);
110 | dest.writeInt(connectionType.ordinal());
111 | dest.writeInt(previousConnectionType.ordinal());
112 | }
113 |
114 | private HostStatus(Parcel in) {
115 | host = in.readString();
116 | port = in.readInt();
117 | previousReachable = (in.readInt() == 1);
118 | reachable = (in.readInt() == 1);
119 | connectionType = ConnectionType.values()[in.readInt()];
120 | previousConnectionType = ConnectionType.values()[in.readInt()];
121 | }
122 |
123 | @Override
124 | public String toString() {
125 | return new Gson().toJson(this);
126 | }
127 | }
128 |
--------------------------------------------------------------------------------
/hostmonitor/src/main/java/net/gotev/hostmonitor/Logger.java:
--------------------------------------------------------------------------------
1 | package net.gotev.hostmonitor;
2 |
3 | /**
4 | * HostMonitor library logger.
5 | * You can provide your own logger delegate implementation, to be able to log in a different way.
6 | * By default the log level is set to DEBUG when the build type is debug, and OFF in release.
7 | * The default logger implementation logs in Android's LogCat.
8 | * @author gotev (Aleksandar Gotev)
9 | */
10 | public class Logger {
11 |
12 | public enum LogLevel {
13 | DEBUG,
14 | INFO,
15 | ERROR,
16 | OFF
17 | }
18 |
19 | public interface LoggerDelegate {
20 | void error(String tag, String message);
21 | void error(String tag, String message, Throwable exception);
22 | void debug(String tag, String message);
23 | void info(String tag, String message);
24 | }
25 |
26 | private LogLevel mLogLevel = BuildConfig.DEBUG ? LogLevel.DEBUG : LogLevel.OFF;
27 |
28 | private LoggerDelegate mDelegate = new DefaultLoggerDelegate();
29 |
30 | private Logger() { }
31 |
32 | private static class SingletonHolder {
33 | private static final Logger instance = new Logger();
34 | }
35 |
36 | public static void resetLoggerDelegate() {
37 | synchronized (Logger.class) {
38 | SingletonHolder.instance.mDelegate = new DefaultLoggerDelegate();
39 | }
40 | }
41 |
42 | public static void setLoggerDelegate(LoggerDelegate delegate) {
43 | if (delegate == null)
44 | throw new IllegalArgumentException("delegate MUST not be null!");
45 |
46 | synchronized (Logger.class) {
47 | SingletonHolder.instance.mDelegate = delegate;
48 | }
49 | }
50 |
51 | public static void setLogLevel(LogLevel level) {
52 | synchronized (Logger.class) {
53 | SingletonHolder.instance.mLogLevel = level;
54 | }
55 | }
56 |
57 | public static void error(String tag, String message) {
58 | if (SingletonHolder.instance.mLogLevel.compareTo(LogLevel.ERROR) <= 0) {
59 | SingletonHolder.instance.mDelegate.error(tag, message);
60 | }
61 | }
62 |
63 | public static void error(String tag, String message, Throwable exception) {
64 | if (SingletonHolder.instance.mLogLevel.compareTo(LogLevel.ERROR) <= 0) {
65 | SingletonHolder.instance.mDelegate.error(tag, message, exception);
66 | }
67 | }
68 |
69 | public static void info(String tag, String message) {
70 | if (SingletonHolder.instance.mLogLevel.compareTo(LogLevel.INFO) <= 0) {
71 | SingletonHolder.instance.mDelegate.info(tag, message);
72 | }
73 | }
74 |
75 | public static void debug(String tag, String message) {
76 | if (SingletonHolder.instance.mLogLevel.compareTo(LogLevel.DEBUG) <= 0) {
77 | SingletonHolder.instance.mDelegate.debug(tag, message);
78 | }
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/hostmonitor/src/main/java/net/gotev/hostmonitor/Status.java:
--------------------------------------------------------------------------------
1 | package net.gotev.hostmonitor;
2 |
3 | /**
4 | * Represents the status of a monitored host.
5 | * @author gotev (Aleksandar Gotev)
6 | */
7 | class Status {
8 | private boolean reachable;
9 | private ConnectionType connectionType;
10 |
11 | public Status() {
12 | reachable = true;
13 | connectionType = ConnectionType.NONE;
14 | }
15 |
16 | public Status(boolean reachable, ConnectionType connectionType) {
17 | this.reachable = reachable;
18 | this.connectionType = connectionType;
19 | }
20 |
21 | public boolean isReachable() {
22 | return reachable;
23 | }
24 |
25 | public void setReachable(boolean reachable) {
26 | this.reachable = reachable;
27 | }
28 |
29 | public ConnectionType getConnectionType() {
30 | return connectionType;
31 | }
32 |
33 | public void setConnectionType(ConnectionType connectionType) {
34 | this.connectionType = connectionType;
35 | }
36 |
37 | @Override
38 | public boolean equals(Object o) {
39 | if (this == o) return true;
40 | if (o == null || getClass() != o.getClass()) return false;
41 |
42 | Status status = (Status) o;
43 |
44 | return reachable == status.reachable && connectionType == status.connectionType;
45 | }
46 |
47 | @Override
48 | public int hashCode() {
49 | int result = (reachable ? 1 : 0);
50 | result = 27 * result + connectionType.hashCode();
51 | return result;
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/hostmonitor/src/main/java/net/gotev/hostmonitor/Util.java:
--------------------------------------------------------------------------------
1 | package net.gotev.hostmonitor;
2 |
3 | import android.content.BroadcastReceiver;
4 | import android.content.ComponentName;
5 | import android.content.Context;
6 | import android.content.pm.PackageManager;
7 |
8 | /**
9 | * Utility methods.
10 | * @author Aleksandar Gotev
11 | */
12 | class Util {
13 |
14 | private static final String LOG_TAG = Util.class.getSimpleName();
15 |
16 | /**
17 | * Private constructor to avoid instantiation.
18 | */
19 | private Util() { }
20 |
21 | /**
22 | * Enables or disables a {@link BroadcastReceiver}.
23 | * Note: be aware that enabling or disabling a component with DONT_KILL_APP on API 14 or 15
24 | * will wipe out any ongoing notifications your app has created.
25 | * http://stackoverflow.com/questions/5624470/enable-and-disable-a-broadcast-receiver
26 | * @param context application context
27 | * @param receiver broadcast receiver class to enable or disable
28 | * @param enabled new status
29 | */
30 | public static void setBroadcastReceiverEnabled(Context context,
31 | Class extends BroadcastReceiver> receiver,
32 | boolean enabled) {
33 | int newState = enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
34 | : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
35 |
36 | Logger.debug(LOG_TAG, (enabled ? "enabling" : "disabling") + " connectivity receiver");
37 |
38 | context.getPackageManager()
39 | .setComponentEnabledSetting(new ComponentName(context, receiver),
40 | newState, PackageManager.DONT_KILL_APP);
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':hostmonitor'
2 |
--------------------------------------------------------------------------------