Broadcast receiver for checking internet connection in android app
Answer to your first question: Your broadcast receiver is being called two times because
You have added two <intent-filter>
Change in network connection :
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
Change in WiFi state:
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
Just use one:<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
.
It will respond to only one action instead of two. See here for more information.
Answer to your second question (you want receiver to call only one time if internet connection available):
Your code is perfect; you notify only when internet is available.
UPDATE
You can use this method to check your connectivity if you want just to check whether mobile is connected with the internet or not.
public boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//should check null because in airplane mode it will be null
return (netInfo != null && netInfo.isConnected());
}
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
if (checkInternet(context)) {
Toast.makeText(context, "Network Available Do operations", Toast.LENGTH_LONG).show();
}
}
boolean checkInternet(Context context) {
ServiceManager serviceManager = new ServiceManager(context);
return serviceManager.isNetworkAvailable()
}
}
ServiceManager.java
public class ServiceManager {
Context context;
public ServiceManager(Context base) {
context = base;
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
}
permissions:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />