Provides a simple way for handling connectivity change events.
- Add the library as a dependency to your
build.gradle
compile 'com.zplesac:connectionbuddy:version@aar'Versions prior to 1.0.5 were hosted on older jCenter repository, and are not available anymore due to trademark issues.
- Initialize ConnectionBuddy instance in your Application class. You'll also need to provide a global configuration by defining ConnectionBuddyConfiguration object.
public class SampleApp extends Application {
@Override
public void onCreate() {
super.onCreate();
ConnectionBuddyConfiguration networkInspectorConfiguration = new ConnectionBuddyConfiguration.Builder(this).build();
ConnectionBuddy.getInstance().init(networkInspectorConfiguration);
}
}All options in ConnectionBuddyConfiguration.Builder are optional. Use only those you really want to customize.
See all default values for config options here.
- Register to connectivity change events in onStart() method of your activity:
@Override
protected void onStart() {
super.onStart();
ConnectionBuddy.getInstance().registerForConnectivityEvents(this, this);
}- Unregister from connectivity change events in onStop() method of your activity:
@Override
protected void onStop() {
super.onStop();
ConnectionBuddy.getInstance().unregisterFromConnectivityEvents(this);
}- React to connectivity change events on onConnectionChange(ConnectivityEvent event) callback method:
@Override
public void onConnectionChange(ConnectivityEvent event) {
if(event.getConnectionState() == ConnectionsState.CONNECTED){
// device has active internet connection
}
else{
// there is no active internet connection on this device
}
}ConnectivityEvent also holds ConnectivityType enum, which defines network connection type currently available on user's device.
You'll also need to clear stored connectivity state for your activity/fragment if it was restored from saved instance state (in order to always have the latest connectivity state). Add to you onCreate() method the following line of code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
if(savedInstanceState != null){
ConnectionBuddyCache.clearInternetConnection(this);
}
}Changelog is available here.
ConnectionBuddy also provides ConnectivityPresenter which can be used as a base presenter for registering to connectivity change events. More detailed example can be found here.
Feedback and code contributions are very much welcome. Just make a pull request with a short description of your changes. By making contributions to this project you give permission for your code to be used under the same license.