Reputation: 33
i developing the project that is uses the internet my problem is that check the application is connected to internet or not i used the fallowing code but error is generated
public void onClick(View v)
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info= cm.getActiveNetworkInfo();
boolean a= cm.getActiveNetworkInfo().isConnectedOrConnecting();
if(a==true){
Toast("Connected");
}
else{
Toast("Not Connected");
}
}
Upvotes: 3
Views: 898
Reputation: 56925
Please try below function . If internet connection is available in device then it will return true otherwise it will return false.
public static boolean CheckInternet(Context context)
{
ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isConnected()) {
return true;
} else if (mobile.isConnected()) {
return true;
}
return false;
}
Add Permission in android manifest file.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Upvotes: 11
Reputation: 2795
try {
ConnectivityManager conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info= conMgr.getActiveNetworkInfo();
if(info != null && info.isConnected())
{
//Internet is there
}
else{
//Internet is not there
}
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
hope it will help you...
Upvotes: 0
Reputation: 41076
Add this in AndroidManifest file , if you haven't done it yet.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
check here,
How can I monitor the network connection status in Android?
Upvotes: 0