Android计算机不在网络上

时间:2016-11-07 10:28:37

标签: java android serversocket

我的应用程序连接到WiFi网络时遇到问题运行网络服务。 我得到以下异常,

下面的openPort()方法中的

java.net.SocketException: socket failed: ENONET (Machine is not on the network)

广播接收器

@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{
        // Line that throws the exception
        return  new ServerSocket(0).getLocalPort();
    }catch (IOException ioe){
        Crashlytics.logException(ioe);
        ioe.printStackTrace();
        return 0;
    }
}

广播接收器仅在主要活动显示时运行。它在第一次运行时工作正常但是当我改变WiFi网络时会发生这种情况。非常感谢帮助世界。

1 个答案:

答案 0 :(得分:0)

使用服务,当网络发生变化或停止网络时启动服务并停止服务。同时检查首先使用发布的相同端口,然后使用该端口。在href中执行任何您想要的任务。 / p>

onStartCommand()