Network Info Example

This example shows how to obtain information about the network connections of a device.

A screenshot of the application.

Note that, in order to access the network information, the application needs to be built with the android.permission.INTERNET permission. The build script takes care of this.

We import the classes and modules that will be needed by the application. The most relevant are the classes from the module.

from import NetworkInterface, SocketException
from android.widget import ListView
from serpentine.activities import Activity
from serpentine.adapters import StringListAdapter

We define a class based on the standard Activity class. This represents the application, and will be used to present a graphical interface to the user.

class NetworkInfoActivity(Activity):

The initialisation method simply calls the base class implementation.

    def __init__(self):

The onCreate method calls the base class implementation before obtaining information about the network interfaces and setting up the user interface.

    def onCreate(self, bundle):
        Activity.onCreate(self, bundle)

The user interfaces consists of a list of strings shown in a ListView widget. We compile the list from the available network interfaces and the addresses assigned to them.

        strings = []
            interfaces = NetworkInterface.getNetworkInterfaces()
            while interfaces.hasMoreElements():

We obtain an interface and the addresses assigned to it.

                interface = interfaces.nextElement()
                addresses = interface.getInetAddresses()
                if addresses.hasMoreElements():

If the interface has at least one address assigned to it then we show the interface name and each of the addresses.

                    while addresses.hasMoreElements():
                        address = addresses.nextElement()
                        values = {address.getHostName(), 
                        for value in values:
                            strings.add("    " + value)

If information about the network interfaces could not be obtained then we simply add a message to the list.

        except SocketException:
            strings.add("No interfaces available")
        adapter = StringListAdapter(strings)
        listView = ListView(self)

Finally, we create an adapter to expose the list of strings to a view and make that view the main view for the application.