Naham Soft Naham Soft - 2 years ago 47
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 Source

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;
        return false;

 // request the service 
 // but make sure that U have surrounded the calling web-service by try and catch
     // 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" />
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download