Reputation: 2886
I understand that if I want to check my internet connection in a Activity everytime network state changes I have to create a BroadcastReceiver.
I have added the permission to my manifest and I have created the following class:
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
final ConnectivityManager connMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isAvailable() || mobile.isAvailable()) {
Log.d("Netowk Available ", "Flag No 1");
}
else
{
Log.d("Network not Available","Network is not available");
}
}
}
The only think I don't understand is how do I make the listener to see the changes. I have Overrided the onResume and onPause in my activity but nothing happens:
@Override
public void onResume() {
super.onResume(); // Always call the superclass method first
registerReceiver(myBroadcast, new IntentFilter());
}
@Override
public void onPause() {
super.onPause(); // Always call the superclass method first
unregisterReceiver(myBroadcast);
}
Upvotes: 1
Views: 675
Reputation: 103
You have to put the BroadcastReceiver inside your Activity, like this answer points out: https://stackoverflow.com/a/4011057/1758048
Regards.
Upvotes: 3