【问题标题】:Would like to find out how long the network has been connected for想知道网络连接了多长时间
【发布时间】:2012-01-10 21:57:50
【问题描述】:

我正在使用以下函数来获取Android设备的本地IP地址:

/**
 * 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;
}

但是,我还需要知道该 IP 地址已连接了多长时间。 我搜索了 InetAddress 结构,但找不到它: http://developer.android.com/reference/java/net/InetAddress.html

有没有其他方法可以查明本地 IP 地址已经存在/连接了多长时间?

【问题讨论】:

    标签: android


    【解决方案1】:

    您需要创建一个后台服务来处理对 ConnectivityManager 进行更改时的监控和记录。

    请注意,您还需要确保服务在启动时启动(由意图 android.intent.action.BOOT_COMPLETED 触发);否则,它只会在用户启动服务后跟踪连接变化。

    【讨论】:

      【解决方案2】:

      AFAIK,您必须注意连接变化(通过ConnectivityManagerCONNECTIVITY_ACTION 和您自己的BroadcastReceiver)并自行跟踪。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-29
      • 1970-01-01
      • 1970-01-01
      • 2020-12-17
      • 2012-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多