1- create new java file (right click the package. new > class > name the file ConnectionDetector.java
2- add the following code to the file
package <add you package name> example com.example.example;
import android.content.Context;
import android.net.ConnectivityManager;
public class ConnectionDetector {
private Context mContext;
public ConnectionDetector(Context context){
this.mContext = context;
}
public boolean isConnectingToInternet(){
ConnectivityManager cm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
if(cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected() == true)
{
return true;
}
return false;
}
}
3- open your MainActivity.java
- the activity where you want to check connection, and do the following
A- create and define the function.
ConnectionDetector mConnectionDetector;</pre>
B- inside the "OnCreate" add the following
mConnectionDetector = new ConnectionDetector(getApplicationContext());
c- to check connection use the following steps
if (mConnectionDetector.isConnectingToInternet() == false) {
//no connection- do something
} else {
//there is connection
}