One of the most basic thinks to learn before creating an application on android is to check if the internet available or not in order to download data like xml freed images YouTube video … and without it the application will crash or it will not run properly in order to solve this problem we are going to use net work class that will help us to check internet status
1
1 – Setup
Create a class called ConnectionDetector and copy and paste the following code in itpackage com.example.radionabeul;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context){
this._context = context;
}
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
}
2 – How to use It
The isConnectingToInternet() inside our class ConnectionDetector will simply return true if the connection is on and false if there is no connection and we are done.1
//declare ConnectionDetector before onCreate method private ConnectionDetector cn;2 add this code to onClick method of your button
cn = new ConnectionDetector(getApplicationContext());
if (cn.isConnectingToInternet()) {
Toast.makeText(getApplicationContext(), "internet is on",
3000).show();
}
else {
Toast.makeText(getApplicationContext(), "internet is off",
3000).show();
}
please do not forget to add ACCESS_NETWORK_STATE and INTERNET permission in AndroidManifest file "AndroidManifest.xml"
and

