If you want to check whether your device connected to Internet or not OR when it turn on/off then adding the observer is the best way. You have to add the observer in activity to check connection is on or off.
Let's see How Detect Network Connectivity Using Observer in Android Device, with example
First, you need to add this library in your application gradle:-
compile 'com.github.pwittchen:networkevents:2.1.6'
Follow this code to check
//Declare NetworkEvents variable
NetworkEvents networkevents;
//Method to add observer for internet connectivity
public void internetChangeListener(){
networkevents = new NetworkEvents(this, new BusWrapper() {
@Override
public void register(Object object) {
}
@Override
public void unregister(Object object) {
}
@Override
public void post(Object event) {
if(event instanceof ConnectivityChanged ){
LogUtils.LOGE("Internet Status", connectivityChanged.getConnectivityStatus() + "");
if (!connectivityChanged.getConnectivityStatus().equals("offline")){
//Code to do your pending work which need connection
}
}
}
});
networkevents.enableInternetCheck();
}
Above method is used to add observer for internet connectivity. Now ,System will notify to post method of above observer with event whenever you switch to another network or internet connection status changed.
0 Comment(s)