I\'m trying to get the moment where user connects to a network, then I thought a BroadcastReceiver is a good approach... The thing that I would like to do is, w
I tried this approach (below) and it worked. Not yet fully tested, but I use similar for receiving battery status. This way there is less code and it does the job.
private BroadcastReceiver networkReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
NetworkInfo networkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (networkInfo != null && networkInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
Log.d(LOG_TAG, "We have internet connection. Good to go.");
} else if (networkInfo != null && networkInfo.getDetailedState() == NetworkInfo.DetailedState.DISCONNECTED) {
Log.d(LOG_TAG, "We have lost internet connection");
}
}
}
};
@Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(networkReceiver, intentFilter);
}
@Override
protected void onPause() {
super.onPause();
if (networkReceiver != null)
unregisterReceiver(networkReceiver);
}