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
First of all we will make a class that will check the connectivity of the network state. So lets create a class :
public class AppStatus {
private static AppStatus instance = new AppStatus();
static Context context;
ConnectivityManager connectivityManager;
NetworkInfo wifiInfo, mobileInfo;
boolean connected = false;
public static AppStatus getInstance(Context ctx) {
context = ctx.getApplicationContext();
return instance;
}
public boolean isOnline() {
try {
connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
connected = networkInfo != null && networkInfo.isAvailable() &&
networkInfo.isConnected();
return connected;
} catch (Exception e) {
System.out.println("CheckConnectivity Exception: " + e.getMessage());
Log.v("connectivity", e.toString());
}
return connected;
}
}
Now Make a new Broadcast receiver class :
public class ConnectivityReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (AppStatus.getInstance(context).isOnline()) {
Intent intent1=new Intent(context,DisplayAct.class);
intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent1);
} else {
Toast.makeText(context, "Please !! Make your network ON", Toast.LENGTH_SHORT).show();
}
}
}
and Now register your broadcast receiver on manifest: