Android: Detect when internet connectivity is connected

Intents are often used to trigger the start of an activity, but you can also set up BroadcastReceivers to listen to global intents which are somewhat like global events.

Examples of such events can be user connecting/disconnecting the headphone or, as the title of this blog, detect when an internet connection is established.

In this example, I start a service when the internet connection is connected. This service does the heavy lifting of logic since broadcast receivers are meant to be very quick, otherwise you'll get system lockups.

Also, services are handy because users would definitely find it annoying if you started a full-screen Activity every time they connected to the internet.

In your manifest file, under the application element add in:

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

This will trigger the InternetConnectionReceiver class whenever these intents are detected.

Now for your broadcast receiver.

public class InternetConnectionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Make sure it's an event we're listening for ...
if (!intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION) &&
!intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION) &&
!intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED))
{
return;
}

ConnectivityManager cm = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));

if (cm == null) {
return;
}

// Now to check if we're actually connected
if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()) {
// Start the service to do our thing
Intent pushIntent = new Intent(context, ContentCheckService.class);
context.startService(pushIntent);

Toast.makeText(context, "Start service", Toast.LENGTH_SHORT).show();
}
}
}

In this case it starts a service called ContentCheckService. You can write whatever code you want in there, but I've added an example of a Toast notification so you can easily check if your broadcast receiver is working properly.

Keep the onReceive() call short! According to the BroadcastReiver docs, you only get 10 seconds before it's killed. This is because it runs on the main thread. Palm it off to a service thread as soon as possible!

More on writing services here.

z0MAy
Now that's what I call service!

Sources

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog