Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Accessing Phone Network/Connectivity Information

Author: Amir Alagic
Published? true -- FormatLanguage: W

Problem:

You want to find information about phones network connectivity

Solution:

You can find out whether your phone is connected to the network, its type of connection, and whether your phone is in roaming territory, using the Connectivity Manager and a NetworkInfo object.

Discussion:

Often you need to know whether your phone can connect to the internet and since roaming can be expensive it is also very useful if we can tell to the app user if he is in roaming (the user who is truly worried about this will disable data roaming using the Settings application). To find this and more we can use the NetworkInfo class in the android.net package.

       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 possibility of connecting to
        that network.*/
        boolean available = ni.isAvailable();
        /*Indicates whether network connectivity is possible.
         A network is unavailable when a persistent
         or semi-persistent condition prevents the possibility
         of connecting to that network. Examples include*/
        boolean connected = ni.isConnected();
        boolean roaming = ni.isRoaming();
        /* Reports the type of network (currently mobile or Wi-Fi) to which the info in this object pertains.*/
        int networkType = ni.getType();
No records found.