我正在开发一个用于短信转发的WiFi应用程序。打开WiFi按钮并打开应用程序后,它会在相应的编辑框中显示像10.0.0.3这样的IP地址,端口号是33300。问题是当应用程序打开时,当我关闭WiFi按钮时,它应该显示为空但仍然显示IPAddress。当我打开WiFi按钮时,它应该再次显示IPAddress。如何在后台检查连续的WiFi地址并显示它在文本框中
public class WifiFragment extends Fragment {
EditText et_portnumber,et_IpAddress;
int port=33300;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.wififragment, container, false);
et_portnumber = (EditText) rootView.findViewById(R.id.etPortnumber);
et_IpAddress= (EditText) rootView.findViewById(R.id.ipaddress);
btn_serverOn=(Button)rootView.findViewById(R.id.btn_Ok);
final String strgetIpdaddress= getIpAddress();
et_IpAddress.setText(strgetIpdaddress);
et_portnumber.setText(port);
}
private String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces .nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip = inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
}
答案 0 :(得分:1)
您应该注册广播接收器以侦听连接状态更改。然后,在您的广播接收器中,您可以轻松确定所连接的网络类型。从那里,如果您的条件得到满足,您可以发送您将在片段中收到的广播,然后您将显示IP地址或您想要的任何内容。 您可以在此页面上找到所有相关信息:http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html