Android Host Monitor


Source link: https://github.com/alexbbb/android-host-monitor

Android Host Monitor

Easily monitor device network state and remote hosts reachability on Android.

Purpose

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.

Setup

Maven

<dependency>
<groupId>net.gotev</groupId>
<artifactId>hostmonitor</artifactId>
<version>2.0</version>
<type>aar</type> </dependency> 

Gradle

dependencies {

  compile 'net.gotev:hostmonitor:2.0@aar' 
}
 

and do a project sync. Check JavaDocs for a complete reference.

Get started

Configuring a remote host reachability check is as simple as:

new HostMonitorConfig(context)

.setBroadcastAction(BuildConfig.APPLICATION_ID)

.add("my.server.com", 80)

.save();

You can do that from wherever you have a Context. What you've done here is the following:

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

When you call save() the settings are persisted and immediately applied.

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:

new HostMonitorConfig(context).save();

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:

new HostMonitorConfig(context).setCheckIntervalInMinutes(15).save();

Bear in mind that more frequent reachability checks drains your battery faster!

You can also set other things such as socket connection timeout and maximum connection attempts before notifying failure. Check JavaDocs.

Unmonitor a host and port

new HostMonitorConfig(context).remove("my.server.com", 80).save();

Remove all the monitored hosts

new HostMonitorConfig(context).removeAll().save();

When there are no hosts left to be monitored, the library automatically shuts down the connectivity monitoring and clears all the scheduled checks.

Reset configuration to factory defaults

If you want to reset the persisted configuration, just invoke:

HostMonitorConfig.reset(context);

This will reset the configuration to factory defaults and will stop any active and scheduled network check.

Receive reachability status changes

To listen for the status, subclass HostMonitorBroadcastReceiver. 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):

public class HostReachabilityReceiver extends HostMonitorBroadcastReceiver {

  @Override
  public void onHostStatusChanged(HostStatus status) {

Log.i("HostReachability", status.toString());

  
}
 
}

and register it as a Broadcast receiver in your manifest:

<receiver
  android:name=".HostReachabilityReceiver"
  android:enabled="true"
  android:exported="false" >
  <intent-filter>

<action android:name="com.yourcompany.yourapp.reachability" />
  </intent-filter> </receiver>

com.yourcompany.yourapp.reachability must be the same string you set as broadcast action in the configuration, otherwise you will not receive reachability events.

You can receive status updates also in your Activity or Service. Here there is an example inside an Activity:

public class YourActivity extends Activity {

private final HostMonitorBroadcastReceiver receiver =

 new HostMonitorBroadcastReceiver() {

@Override

public void onHostStatusChanged(HostStatus status) {

Log.i("HostMonitor", status.toString());

}

 
}
;

@Override
  protected void onResume() {

super.onResume();

receiver.register(this);

  
}

@Override
  protected void onPause() {

super.onPause();

receiver.unregister(this);

  
}
 
}

A partial wake lock is automatically held for the entire execution of the onHostStatusChanged method and is released as soon as the method returns.

Logging

By default the library logging is disabled. You can enable debug log by invoking:

Logger.setLogLevel(LogLevel.DEBUG);

The library logger uses android.util.Log, but you can override that by providing your own logger implementation like this:

Logger.setLoggerDelegate(new Logger.LoggerDelegate() {

  @Override
  public void error(String tag, String message) {

//your own implementation here
  
}

@Override
  public void error(String tag, String message, Throwable exception) {

//your own implementation here
  
}

@Override
  public void debug(String tag, String message) {

//your own implementation here
  
}

@Override
  public void info(String tag, String message) {

//your own implementation here
  
}
 
}
);

Issues

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 :)

Contribute

  • Do you have a new feature in mind?
  • Do you know how to improve existing docs or code?
  • Have you found a bug?

Contributions are welcome and encouraged! Just fork the project and then send a pull request. Be ready to discuss your code and design decisions :)

Do you like the project?

Put a star, spread the word and if you want to offer me a free beer,

License

Copyright (C) 2015-2016 Aleksandar Gotev  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. 

Resources

A helper class to write files in external android storage.

Android library for streamlining SharedPreferences.

A very simple color picker.

Android ImageViews animated by Ken Burns Effect.

Provides the Floating Action Button Toolbar as specified in the Material Design Guide in a simple library.

Emmet is an protocol based data-transfer for Android Wear.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes