Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android connect to internet event

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

like image 762
Buda Gavril Avatar asked May 19 '11 09:05

Buda Gavril


2 Answers

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);
like image 101
Francesco Laurita Avatar answered Sep 19 '22 00:09

Francesco Laurita


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.

like image 45
Mark Allison Avatar answered Sep 20 '22 00:09

Mark Allison