Naham Soft Naham Soft - 1 year ago 111
PHP Question

how to listen to change in internet connection android studio?

I already create an android app which use the web services to send and retrieve json data

but the problem when I make a request while the device in online it works fine but when the device go offline the app stuck and print Null Exception error

is there a way to listen to the internet connection and ignore the process if possible

please help. Thanks so much

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" />