花了很多小时来寻找方法(由谷歌和这个网站),但我找不到一个正确的代码来写入TextView自己的安卓ip地址。
我试了很多很多代码,但是没有人运行。
获取android的IP地址并将其放入TextView的正确方法是什么?
谢谢。
public class MainActivity extends Activity {
private TextView textView1;
private String tag;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1 =(TextView)findViewById(R.id.textView1);
getLocalIpAddress();
String ip = getLocalIpAddress();
textView1.setText("IP:"+ip);
}
public String getLocalIpAddress()
{
try
{
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();)
{
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
{
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress())
{
return inetAddress.getHostAddress().toString();
}
}
}
}
catch (SocketException ex)
{
Log.e(tag, ex.toString());
}
return "";
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="19dp"
android:text="TextView" />
发布于 2012-11-15 21:08:54
TextView tv = (TextView) findViewById(R.id.tv);
WifiManager wim= (WifiManager) getSystemService(WIFI_SERVICE);
List<WifiConfiguration> l = wim.getConfiguredNetworks();
WifiConfiguration wc = l.get(0);
tv.append("\n"+ Formatter.formatIpAddress(wim.getConnectionInfo().getIpAddress()));
AndroidManifest.xml权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
或者,您可以使用以下代码(不使用格式化程序):
public String getLocalIpAddress()
{
try
{
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();)
{
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
{
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress())
{
return inetAddress.getHostAddress().toString();
}
}
}
}
catch (SocketException ex)
{
Log.e(tag, ex.toString());
}
return "";
}
发布于 2013-06-15 21:38:01
尝尝这个
String IP;
WifiManager wim= (WifiManager) getSystemService(WIFI_SERVICE);
List<WifiConfiguration> l = wim.getConfiguredNetworks();
WifiConfiguration wc = l.get(0);
IP=Formatter.formatIpAddress(wim.getConnectionInfo().getIpAddress());
tv.setText(IP);
https://stackoverflow.com/questions/13406180
复制相似问题