Search code examples
androideventsconnection

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


Solution

  • 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);