I had a problem Starting a network service when my application connects to a WiFi network. I get the following exception,
java.net.SocketException: socket failed: ENONET (Machine is not on the network) in the openPort () method below
BroadcastReceiver
@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; } }
BroadcastService
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{
This broadcast receiver only works when the main activity is shown. and it works great the first time it starts, but when I change the WiFi network, this happens. The world of help is commendable.
source share