Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

java - InetAddress.getByName on Android

I do a:

java.net.InetAddress serverAddr;
try {
    serverAddr = java.net.InetAddress.getByName(Server.SERVERNAME);
}
catch (java.net.UnknownHostException exception) {
    //System.err.println ("wrong server name !!!");
    HelloWorldActivity.tv.setText("wrong server name !!!");
    return;
}

in my android application, but it's never resoling the hostname, it always throws an exception, no matter what name I use.


But using the internet on the same emulator works, and I've added

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

to AndoidManifest.xml

and here's the server class for those who assume I have none

public class Server
{
    public static String SERVERNAME = "monster.idsoftware.com";
    public static String SERVERIP = "209.85.129.99";
    public static int SERVERPORT = 27950;
    public static int PROTOCOL = 68;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I was having the similar issue and I found out that in some versions of android (from honeycombs) it's not allowed by default to perform network operation from main thread. So you can resolve it in 2 ways. Perform operation in different thread or allow to make network operation in main thread. To do that use something like this:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitNetwork().build();
StrictMode.setThreadPolicy(policy);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...