Safe background networking
Listing 28.4 Checking for background network availability (PollService.java)
public class PollService extends IntentService {
private static final String TAG = "PollService";
...
@Override
protected void onHandleIntent(Intent intent) {
if (!isNetworkAvailableAndConnected()) {
return;
}
Log.i(TAG, "Received an intent: " + intent);
}
private boolean isNetworkAvailableAndConnected() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
boolean isNetworkAvailable = cm.getActiveNetworkInfo() != null;
boolean isNetworkConnected = isNetworkAvailable &&
cm.getActiveNetworkInfo().isConnected();
return isNetworkConnected;
}
}
The logic for checking network availability is in isNetworkAvailableAndConnected(). Toggling the
background data setting to disallow downloading data in the background disables the network entirely
for use by background services. In this case, ConnectivityManager.getActiveNetworkInfo() returns
null, making it appear to the background service as though there is no active network available, even if
there really is.
If the network is available to your background service, it gets an instance of
android.net.NetworkInfo representing the current network connection. The code then checks
whether the current network is fully connected by calling NetworkInfo.isConnected().
If the app does not see a network available, or the device is not fully connected to a network,
onHandleIntent(Intent) will return without executing the rest of the method (and in turn will not
try to download data, once you have added the code to do so). This is good practice because your app
cannot download any data if it is not connected to the network.
One more thing. To use getActiveNetworkInfo(), you also need to acquire the
ACCESS_NETWORK_STATE permission. As you have seen, permissions are managed in your manifest.
Listing 28.5 Acquiring network state permission (AndroidManifest.xml)
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.bignerdranch.android.photogallery" >
<application
... >
...