安卓机器不在网络上
2022-09-04 04:55:47
我在运行网络服务时遇到问题,当我的应用连接到 WiFi 网络时。我遇到以下异常,
java.net.SocketException: socket failed: ENONET (Machine is not on the network)
在 openPort() 方法波纹管中
广播接收者
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (networkInfo.getState() == NetworkInfo.State.CONNECTED) {
welcomeService = new BroadcastService(context, "Welcome");
Log.i(TAG, "onReceive: SUPPLICANT-STATE ---> Connected");
//do something
if (!serviceRegistered) {
welcomeService.registerService();
serviceRegistered = true;
}
}
if (networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Log.i(TAG, "onReceive: SUPPLICANT-STATE ---> Disconnected");
//do something
unRegisterService();
}
}
}
public void unRegisterService() {
if (serviceRegistered && welcomeService != null) {
welcomeService.unregisterService();
serviceRegistered = false;
}
}
广播服务
public void registerService() {
NsdServiceInfo serviceInfo = new NsdServiceInfo();
serviceInfo.setServiceName(mServiceName);
serviceInfo.setServiceType("_http._tcp.");
serviceInfo.setPort(openPort());
mNsdManager = (NsdManager) mContext.getSystemService(Context.NSD_SERVICE);
mNsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);
}
private int openPort() {
try{
// Line that throws the exception
return new ServerSocket(0).getLocalPort();
}catch (IOException ioe){
Crashlytics.logException(ioe);
ioe.printStackTrace();
return 0;
}
}
广播接收器仅在显示主要活动时运行。它在第一次运行时工作正常,但是当我更改WiFi网络时,就会发生这种情况。帮助世界得到极大的赞赏。