I am developing an android broadcast receiver for checking internet connection.
The problem is that my broadcast receiver is being called two times. I want it to get
manifest:
class for receiver:
public class ConnectivityReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
switch (action) {
case ConnectivityManager.CONNECTIVITY_ACTION:
DebugUtils.logDebug("BROADCAST", "network change");
if(NetworkUtils.isConnect()){
//do action here
}
break;
}
}
}
and classs utils like example:
public class NetworkUtils {
public static boolean isConnect() {
ConnectivityManager connectivityManager = (ConnectivityManager) Application.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Network[] netArray = connectivityManager.getAllNetworks();
NetworkInfo netInfo;
for (Network net : netArray) {
netInfo = connectivityManager.getNetworkInfo(net);
if ((netInfo.getTypeName().equalsIgnoreCase("WIFI") || netInfo.getTypeName().equalsIgnoreCase("MOBILE")) && netInfo.isConnected() && netInfo.isAvailable()) {
//if (netInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
Log.d("Network", "NETWORKNAME: " + netInfo.getTypeName());
return true;
}
}
} else {
if (connectivityManager != null) {
@SuppressWarnings("deprecation")
NetworkInfo[] netInfoArray = connectivityManager.getAllNetworkInfo();
if (netInfoArray != null) {
for (NetworkInfo netInfo : netInfoArray) {
if ((netInfo.getTypeName().equalsIgnoreCase("WIFI") || netInfo.getTypeName().equalsIgnoreCase("MOBILE")) && netInfo.isConnected() && netInfo.isAvailable()) {
//if (netInfo.getState() == NetworkInfo.State.CONNECTED) {
Log.d("Network", "NETWORKNAME: " + netInfo.getTypeName());
return true;
}
}
}
}
}
return false;
}
}