我正在开发一个Android应用程序,我希望它显示网络上的所有IP地址,我已经在一个运行良好的java应用程序中使用它,但是当我在Android应用程序中使用它时它会在到达时崩溃InetAddress.getLocalHost()
,这可以在Android应用程序上运行,还是有另外一种方法可以做到这一点?
码
InetAddress localhost = null;
try {
localhost = InetAddress.getLocalHost(); // it crashes here
System.out.println("after");
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
System.out.println("the application stoped here");
e1.printStackTrace();
}
System.out.println("3");
// this code assumes IPv4 is used
byte[] ip = localhost.getAddress();
for (int i = 0; i <= 254; i++) {
ip[3] = (byte) i;
InetAddress address = null;
try {
address = InetAddress.getByAddress(ip);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PingThread p = new PingThread(address);
p.start();
}
答案 0 :(得分:2)
您可以通过在try / catch之前将其添加到代码来解决此问题:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
...这是你的AndroidManifest文件:
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
</uses-permission>
有关StrictMode的更多详细信息,请参阅Android Docs。