Chapter 18. System and Device Control

Android provides a good compromise between the needs of the carriers for control and the needs of developers for device access. This chapter looks at some of the informational and control APIs that are publicly available that allow Android developers to explore and control the extensive hardware facilities provided by the system and to deal with the wide range of hardware it runs on, from 2-inch cell phones to 10-inch tablets and netbooks.

18.1 Accessing Phone Network/Connectivity Information

Amir Alagic

Problem

You want to find information about the device’s current network connectivity.

Solution

Determine whether your phone is connected to the network, the type of connection, and whether it’s in roaming territory using the ConnectivityManager class and a NetworkInfo object.

Discussion

Often you need to know whether the device you are running on can currently connect to the internet, and, since roaming can be expensive, it is also very useful if you can tell the user whether he is roaming. To do this and more we can use the NetworkInfo class in the android.net package, as in Example 18-1.

Example 18-1. Getting network information
    ConnectivityManager connManager =
        (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = connManager.getActiveNetworkInfo();
    /* Indicates whether network connectivity is possible.
    A network is unavailable when a persistent or semi-persistent
 condition prevents the ...

Get Android Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.