I am checking the connectivity of the device as suggested in this question with the following code:
final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.getState() == NetworkInfo.State.CONNECTED) {
//notify user you are online
} else {
//notify user you are not online
}
I have this in my main Activity and it works fine, but what I would like to do now is to check the internet connection everytime the application fires up, sometimes the app is left in some state and then the internet is disconnected, so when it opens up again it does not go through the main activity so nothing is checked.
As suggested in this question I have followed this tutorial on monitoring internet activity with BroadcastReceiver and I am trying to display and AlertDialog when noConnectivity is true, but nothing happens.
This is my code, using the tutorial mentioned above:
public class MyActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
registerReceivers() ;
(..my activity code goes here...)
}
private void noInternet()
{
Intent myIntent = new Intent(this, NoInternetActivity.class);
startActivity(myIntent);
}
/*
* method to be invoked to register the receiver
*/
private void registerReceivers() {
registerReceiver(mConnReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
private void alert()
{
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("internet connection");
alertDialog.setMessage("To use this app you need intenet connection");
alertDialog.setButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
}
});
alertDialog.show();
}
private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
// do application-specific task(s) based on the current network state, such
// as enabling queuing of HTTP requests when currentNetworkInfo is connected etc.
if(noConnectivity)
{
alert();
noInternet();
}
}
};
}
but neither alert()
or noInternet()
gets fired up.
Hope you can help me out. Thanks