With the current design, our service will start automatically at boot time and attempt to connect to the cloud and retrieve the latest updates approximately every minute. One problem with the current design is that the service will try to connect even when there’s no Internet connection available. This adds unnecessary attempts to wake up the radio and connect to the server, all of which taxes the battery. Imagine how many wasteful attempts would be made while your phone is in flight mode on a cross-country flight. This highlights some of the inherit constraints when programming for mobile devices: we’re limited by the battery life and network connectivity.
A better approach is to listen to network availability broadcasts and use that information to intelligently turn off the service when the Internet is unavailable and turn it back on when data connection comes back up. The system does send an intent whenever connection availability changes. Another system service allows us to find out what changed and act accordingly.
In this case, we’re
creating another receiver,
NetworkReceiver, shown in Example 11-8. Just as before, we need to create a Java class
and then register it via the Android manifest file.
Example 11-8. NetworkReceiver.java
package com.marakana.yamba6; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.util.Log; ...