【发布时间】:2017-05-03 16:52:56
【问题描述】:
我正在创建一个 android 应用程序,通过 wifi 链接和传输套接字数据包到服务器。为此,必须定义所连接服务器的 IP 地址。我使用下面的函数来获取 IP 地址。当我硬编码 SERVER_IP = "0";该应用程序正常运行。请帮忙!
private final String SERVER_IP = getIpAddr();
public String getIpAddr() {
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
String ipString = String.format(
"%d.%d.%d.%d",
(ip & 0xff),
(ip >> 8 & 0xff),
(ip >> 16 & 0xff),
(ip >> 24 & 0xff));
return ipString;
}
以上设置完成后,我在 OnCreate 函数上运行了以下代码。
class ClientThread implements Runnable {
@Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
一旦发生这种情况,我的 android 应用程序将停止工作。
这是出现的错误:
Java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“android.content.Context android.content.Context.getApplicationContext()”
【问题讨论】:
-
尝试使用 ActivityName.this.getApplicationContext() 获取上下文
-
谢谢。加 1。
标签: java android sockets tcp tcpclient