Hello I have application based on data retrieved over internet...
How can I handle my app in case there is no connection available?
I can detect connection with
ConnectivityManager cm = (ConnectivityManager)
getSystemService(this.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo().isConnectedOrConnecting();
It works fine... But how can I prevent Force Erros when I know there is no connection? I would like a message to be shown - something like: "Sorry! There is no internet connection available!" and not my application to crush...
In android, we can determine the internet connection status easily by using getActiveNetworkInfo() method of ConnectivityManager object. Following is the code snippet of using the ConnectivityManager class to know whether the internet connection is available or not.
/**
* Checks if the device has Internet connection.
*
* @return <code>true</code> if the phone is connected to the Internet.
*/
public static boolean hasConnection() {
ConnectivityManager cm = (ConnectivityManager) MbridgeApp.getContext().getSystemService(
Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiNetwork != null && wifiNetwork.isConnected()) {
return true;
}
NetworkInfo mobileNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mobileNetwork != null && mobileNetwork.isConnected()) {
return true;
}
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
return true;
}
return false;
}
getActiveNetworkInfo() may return null, so you will get a force close, but you can do that:
ConnectivityManager cm = (ConnectivityManager)
getSystemService(this.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (null == ni)
return false;
return ni.isConnectedOrConnecting();
Then the check is simple:
if (networkAvailable()) // << your method from above
{
// Do stuff
}
else
{
Toast.makeToast(yourcontext, "No network available", Toast.LENGTH_LONG).show();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With