I’am developing an application for android, which needs network in order to retrieve some information from an xml file. I’ve got this code, that looking for if the users has enabled the network:
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
return true;
}
return false;
}
I use this function this way:
boolean connected = isOnline();
if(connected)
getLocation();
else
showDialogNetwork();
The function showDialogNetwork():
public void showDialogNetwork() {
new AlertDialog.Builder(this)
.setMessage("No network")
.setTitle("Error")
.setCancelable(false)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// launch settings
Intent settings = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
startActivity(settings);
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
// finish activity
finish();
}
})
.show();
}
If the network on the device is disabled the showDialogNetwork() will open the network tab in the settings menu. But when the users turn on the WiFi, and the application is running in the background, it doesn’t “understand” that the network is turned on. I need the “kill” the app after the network is turned on, to get the information from the internet. How can I constantly check if the network has change state during run time of my application? Thanks in advance, guys 🙂
Create a
BroadcastReceiverwith anIntentFilterwhich ‘listens’ for…You can either register for that in code or if you register the
BroadcastReceiverin your manifest then use the following for the<intent-filter>See WifiManager.WIFI_STATE_CHANGED_ACTION
To also monitor mobile Internet connectivity change you would ‘listen’ for…
ConnectivityManager.CONNECTIVITY_ACTION
In this case use the following in the manifest…