我想在我的应用程序中使用以下代码:
InetAddress inetAddress;
try {
inetAddress = InetAddress.getByName(hostname);
} catch (UnknownHostException e) {
return -1;
}
它在我测试过的大多数设备上运行良好,但在 Nexus S Europe 和华为设备上,它会抛出异常。
cannot establish route for 192.168.010.200: unkown host
我已经尝试在我的 Application 类中使用以下代码修复它,但没有成功:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitNetwork().build();
StrictMode.setThreadPolicy(policy);
我也尝试过使用 AsyncTask,但我遇到了同样的错误。这是我使用的代码:
private int mInetAddr = -1;
private boolean mInetAck = false; // Acknowledgement
private class AsyncInetAddress extends AsyncTask<String, Void, Void>
{
@Override
protected Void doInBackground(String... hostname)
{
InetAddress inetAddress;
try
{
inetAddress = InetAddress.getByName(hostname[0]);
}
catch (UnknownHostException e)
{
mInetAddr = -1;
return null;
}
byte[] addrBytes;
int addr;
addrBytes = inetAddress.getAddress();
addr = ((addrBytes[3] & 0xff) << 24)
| ((addrBytes[2] & 0xff) << 16)
| ((addrBytes[1] & 0xff) << 8)
| (addrBytes[0] & 0xff);
mInetAddr = addr;
return null;
}
@Override
protected void onPostExecute(Void result)
{
mInetAck = true; // Acknowledgement
}
}
您知道我该如何解决这个问题吗?
谢谢。
编辑:我在其他一些设备上试过,问题看起来只出现在版本 4.0.* 上。在 2.*、3.* 和 4.1+ 上运行良好。
现在问题出在那一行:
if (!connMgr.requestRouteToHost(2, inetAddr))
其中 inetAddr = -938825536
。第一个参数是 MMS 类型。在运行 4.0.3 或 4.0.4 的设备下,条件始终为真。
最佳答案
首先,您遇到的具体错误是什么?
这可能不是设备的问题,而是您运行的 Android 版本的问题。
并尝试改变这一点:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitNetwork().build();
StrictMode.setThreadPolicy(policy);
到:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
关于某些设备上的 Android 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14340518/