Elvis Oliveira
Elvis Oliveira

Reputation: 941

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?

Upvotes: 0

Views: 149

Answers (2)

Jeffrey Blattman
Jeffrey Blattman

Reputation: 22637

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
        }
}

Upvotes: 2

Ethan Liou
Ethan Liou

Reputation: 1632

public boolean online() {
    ConnectivityManager manager =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = manager.getActiveNetworkInfo();
    return info != null && info.isConnectedOrConnecting();
}

Upvotes: 0

Related Questions