我已经注册了一个Android广播接收器来检查Wifi何时可用(请注意我已在清单中添加了ACCESS_NETWORK_STATE):
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
// register for connectivity related events
androidContext.registerReceiver(this, filter, null, handler);
...
然后,当我收到广播事件时,我检查它是否是Wifi,以及NetworkInfo.isConnected()是否返回true。如果是这样,我尝试检索Wifi接口IP地址:
@Override
public void onReceive(Context context, Intent intent)
{
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
if (activeNetwork != null) {
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI && activeNetwork.isConnected()) {
RCLogger.w(TAG, "Connectivity event: WIFI");
WifiManager wifiMgr = (WifiManager) androidContext.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
stringAddress = Formatter.formatIpAddress(ip);
}
此时我希望stringAddress是Wifi接口的有效IP地址,而不是0.0.0.0。
这似乎是一个时间问题,因为如果我在我收到事件后尝试检索IP地址之前睡了5秒钟,它运行正常并且使用了使用过的Wifi IP地址
谢谢, 安东尼