Search code examples
androidconnectionaction

How to be advised when android has internet connection


I want to create an application that performs a particular action when the device has a internet connection. Is this possible in android?


Solution

  • You can list for a particular intent. Define a receiver like this,

        <receiver android:name=".NetworkReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>
    

    and in your receive, inspect the network state like,

    @Override
    public void onReceive(Context ctx, Intent intent) {
        if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
            NetworkInfo info = intent
                    .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            String typeName = info.getTypeName();
            String subtypeName = info.getSubtypeName();
                        boolean available = info.isAvailable();
                        // etc
            }
    }