Swathin Swathin - 5 months ago 10
Android Question

Do i need to check whether the phone is in offline mode in every time a new activity is called?

I have written a code to check whether the phone is currently online or not. But my question is do i need to check whether the phone is in offline mode in every time a new activity is called? if yes then what is the better way to code that?

The code to check whether phone is online or offline is like this:

private boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nwrkInfo = cm.getActiveNetworkInfo();
if (nwrkInfo != null && nwrkInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}


The above code will return true when the phone is online otherwise false. Is there any oops technique so that i can access this method from other activity?

Answer

Is there any oops technique so that i can access this method from other activity?

You can create a Utility class, and declare this method isOnline() as a static function over there (protected or public depending on your package design).

protected static boolean isOnline()

From any activity call it like this

boolean isPhoneOnline = Utility.isOnline();

Hope this helps.