Is there an event that tells me that the device has connected to the INTERNET (3G or wifi)? I need to start some requests only after the device connects to the INTERNET. The code needs to support Android 2.1. Thanks
You can use a Broadcast receiver and wait for the action ConnectivityManager.CONNECTIVITY_ACTION
Here the doc
Ex:
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] info = connectivity.getAllNetworkInfo();
//Play with the info about current network state
}
}
};
intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
Use a Broadcast receiver which will get called whenever the network state changes:
private NetworkStateReceiver mNetSateReceiver = null;
private class NetworkStateReceiver extends BroadcastReceiver
{
@Override
public void onReceive( Context context, Intent intent )
{
// Check the network state to determine whether
// we're connected or disconnected
}
}
@Override
public void onCreate()
{
registerReceiver( mNetSateReceiver, new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION ) );
}
@Override
public void onDestroy()
{
save();
unregisterReceiver( mNetSateReceiver );
}
onReceive will get called whenever the network state changes, and you can use the techniques detailed in the other answer to determine whether you're actually connected or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With