0

I am using the following function to get the local IP address of the Android device:

/**
 * Loops through all network interfaces to find one with a connection
 * @return the IP of the connected network device, on error returns null
 */
public String getIPAddress() 
{
    String strIPaddress = null;

    try 
    {
        Enumeration<NetworkInterface> enumNetIF = NetworkInterface.getNetworkInterfaces();
        NetworkInterface netIF = null;

        //loop whilst there are more interfaces
        while(enumNetIF.hasMoreElements()) 
        {
            netIF = enumNetIF.nextElement();

            for (Enumeration<InetAddress> enumIP = netIF.getInetAddresses(); enumIP.hasMoreElements();) 
            {
                InetAddress inetAddress = enumIP.nextElement();

                //check for valid IP, but exclude the loopback address
                if(inetAddress.isLoopbackAddress() != true)
                {
                    strIPaddress = inetAddress.getHostAddress();
                    break;
                }
            }
        }
    } 
    catch (SocketException e) 
    {
        Log.e(TAG, e.getMessage());
    }

    return strIPaddress;
}

However, I also need to know for how long this IP address has been connected for. I've searched through the InetAddress structure and couldn't find it: http://developer.android.com/reference/java/net/InetAddress.html

is there another way to find out for how long the local IP address has existed / connected ?

Someone Somewhere
  • 23,475
  • 11
  • 118
  • 166

2 Answers2

0

AFAIK, you would have to watch for connectivity changes (via ConnectivityManager, CONNECTIVITY_ACTION, and your own BroadcastReceiver) and track it yourself.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • I agree, it does look like I'd need to catch the relevant broadcasts. This code sample has something to get started with: http://stackoverflow.com/questions/5276032/connectivity-action-intent-recieved-twice-when-wifi-connected – Someone Somewhere Feb 04 '12 at 20:03
0

You'll need to create a background service to handle the monitoring and record when changes are made to the ConnectivityManager.

Note that you'll want to make sure the service starts at boot (triggered by the intent android.intent.action.BOOT_COMPLETED), too; otherwise, it will only keep track of connection changes after the user launches the service.

Mike Fahy
  • 5,487
  • 4
  • 24
  • 28