Naham Soft Naham Soft - 7 months ago 8
PHP Question

How to listen to change in internet connection in my Android app?

I already created an android app which uses a web service to send and retrieve JSON data.

When I make a request while the device is online it works fine but when the device goes offline the app is stuck and prints Null Pointer Exception error.

Is there a way to listen to the internet connection?

Answer

before request the web service call this method

private boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo NInfo = cm.getActiveNetworkInfo();

    if (NInfo != null && NInfo.isConnectedOrConnecting())
        return true;
    else
        return false;
}

if(isOnline()){
 // request the service 
 // but make sure that U have surrounded the calling web-service by try and catch
try{
     // here make your request when the connection go offline the app will    catch   the error and ignore the process 
}catch (Exception e) {
}

add this permission

 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Comments