如何检测连接到wifi网络的设备

How detect the devices connected to wif network

你好

您知道如何检测连接到 wifi 网络的设备吗? 我使用此 java 代码源来检测连接到我的家庭网络的设备:

import java.io.IOException;
import java.net.ServerSocket;



import android.net.nsd.NsdManager;
import android.net.nsd.NsdManager.DiscoveryListener;
import android.net.nsd.NsdManager.RegistrationListener;
import android.net.nsd.NsdManager.ResolveListener;
import android.net.nsd.NsdServiceInfo;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;

@SuppressLint("NewApi")
public class MainActivity extends Activity {

    NsdManager.RegistrationListener mRegistrationListener;
    NsdManager.DiscoveryListener mDiscoveryListener;

    String mServiceName;
    NsdServiceInfo mServiceInfo;
    ServerSocket mServerSocket;
    int mLocalPort;

    NsdManager mNsdManager;

    final String TAG = "---Networking";
    final String SERVICE_TYPE = "_http._tcp.";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initialize a server socket on the next available port.
        try {
            mServerSocket = new ServerSocket(0);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // Store the chosen port.
        mLocalPort =  mServerSocket.getLocalPort();
        registerService(mLocalPort);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    public void registerService(int port) {
        // Create the NsdServiceInfo object, and populate it.
        mServiceInfo  = new NsdServiceInfo();

        // The name is subject to change based on conflicts
        // with other services advertised on the same network.

        mServiceInfo.setServiceName("NsdChat");
        mServiceInfo.setServiceType("_http._tcp.");
        mServiceInfo.setPort(port);

        mNsdManager = (NsdManager) getApplicationContext().getSystemService(Context.NSD_SERVICE);

        initializeRegistrationListener();
        initializeDiscoveryListener();

        mNsdManager.registerService(
                mServiceInfo, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);

        mNsdManager.discoverServices(
                SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);
    }

    public void initializeRegistrationListener() {
        mRegistrationListener = new NsdManager.RegistrationListener() {

            @Override
            public void onServiceRegistered(NsdServiceInfo NsdServiceInfo) {
                // Save the service name.  Android may have changed it in order to
                // resolve a conflict, so update the name you initially requested
                // with the name Android actually used.
                mServiceName = NsdServiceInfo.getServiceName();
                Log.d(TAG, "Service name: " + mServiceName);
                Log.d(TAG , "Port number: " + mLocalPort);
            }

            @Override
            public void onRegistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
                // Registration failed!  Put debugging code here to determine why.
                Log.d(TAG , "Registration Failed! Error code: " + errorCode);
            }

            @Override
            public void onServiceUnregistered(NsdServiceInfo arg0) {
                // Service has been unregistered.  This only happens when you call
                // NsdManager.unregisterService() and pass in this listener.
                Log.d(TAG , "Service unregistered.");
            }

            @Override
            public void onUnregistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
                // Unregistration failed.  Put debugging code here to determine why.
                Log.d(TAG , "Unregistration failed!");
            }
        };
    }

    public void initializeDiscoveryListener() {

        // Instantiate a new DiscoveryListener
        mDiscoveryListener = new NsdManager.DiscoveryListener() {

            //  Called as soon as service discovery begins.
            @Override
            public void onDiscoveryStarted(String regType) {
                Log.d(TAG , "Service discovery started");
            }

            @Override
            public void onServiceFound(NsdServiceInfo service) {
                // A service was found!  Do something with it.
                Log.d(TAG, "Service discovery success: " + service);
                if (!service.getServiceType().equals(SERVICE_TYPE)) {
                    // Service type is the string containing the protocol and
                    // transport layer for this service.
                    Log.d(TAG, "Unknown Service Type: " + service.getServiceType());
                } else if (service.getServiceName().equals(mServiceName)) {
                    // The name of the service tells the user what they'd be
                    // connecting to. It could be "Bob's Chat App".
                    Log.d(TAG, "Same machine: " + mServiceName);
                } else if (service.getServiceName().contains("NsdChat")){
                    mNsdManager.resolveService(service, new NsdManager.ResolveListener() {

                        @Override
                        public void onServiceResolved(NsdServiceInfo serviceInfo) {
                            // TODO Auto-generated method stub
                            Log.d(TAG, "Resolving service...");
                        }

                        @Override
                        public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) {
                            // TODO Auto-generated method stub
                            Log.d(TAG, "Service resolve failed!");
                        }
                    });
                }
            }

            @Override
            public void onServiceLost(NsdServiceInfo service) {
                // When the network service is no longer available.
                // Internal bookkeeping code goes here.
                Log.e(TAG, "service lost: " + service);
            }

            @Override
            public void onDiscoveryStopped(String serviceType) {
                Log.i(TAG, "Discovery stopped: " + serviceType);
            }

            @Override
            public void onStartDiscoveryFailed(String serviceType, int errorCode) {
                Log.e(TAG, "Discovery failed: Error code: " + errorCode);
                mNsdManager.stopServiceDiscovery(this);
            }

            @Override
            public void onStopDiscoveryFailed(String serviceType, int errorCode) {
                Log.e(TAG, "Discovery failed: Error code: " + errorCode);
                mNsdManager.stopServiceDiscovery(this);
            }
        };
    }
}

但是我有这个结果。在此结果中,端口号和主机名为空。

  02-15 19:10:58.205  21554-21554/com.example.fatma.myapplication W/asset﹕ AssetManager-->addDefaultAssets CIP path not exsit!
    02-15 19:10:58.490  21554-21554/com.example.fatma.myapplication V/PhoneWindow﹕ DecorView setVisiblity: visibility = 4
    02-15 19:10:58.567  21554-21591/com.example.fatma.myapplication D/---Networking﹕ Service discovery started
    02-15 19:10:58.572  21554-21591/com.example.fatma.myapplication D/---Networking﹕ Service discovery success: name: NsdChattype: _http._tcp.host: nullport: 0txtRecord: null
    02-15 19:10:58.594  21554-21591/com.example.fatma.myapplication D/---Networking﹕ Service discovery success: name: NsdChattype: _http._tcp.host: nullport: 0txtRecord: null
    02-15 19:10:58.597  21554-21591/com.example.fatma.myapplication D/---Networking﹕ Service discovery success: name: NsdChat (2)type: _http._tcp.host: nullport: 0txtRecord: null
    02-15 19:10:58.598  21554-21591/com.example.fatma.myapplication D/---Networking﹕ Service discovery success: name: NsdChat (2)type: _http._tcp.host: nullport: 0txtRecord: null
    02-15 19:10:58.598  21554-21591/com.example.fatma.myapplication D/---Networking﹕ Service resolve failed!
    02-15 19:10:58.599  21554-21591/com.example.fatma.myapplication D/---Networking﹕ Service resolve failed!
    02-15 19:10:58.601  21554-21591/com.example.fatma.myapplication D/---Networking﹕ Service resolve failed!
    02-15 19:10:58.625  21554-21554/com.example.fatma.myapplication V/PhoneWindow﹕ DecorView setVisiblity: visibility = 0
    02-15 19:10:58.835  21554-21554/com.example.fatma.myapplication D/libEGL﹕ loaded /system/lib/egl/libEGL_mali.so
    02-15 19:10:58.859  21554-21554/com.example.fatma.myapplication D/libEGL﹕ loaded /system/lib/egl/libGLESv1_CM_mali.so
    02-15 19:10:58.879  21554-21554/com.example.fatma.myapplication D/libEGL﹕ loaded /system/lib/egl/libGLESv2_mali.so
    02-15 19:10:58.915  21554-21554/com.example.fatma.myapplication I/﹕ appName=com.example.fatma.myapplication, acAppName=eu.chainfire.cfbench
    02-15 19:10:58.915  21554-21554/com.example.fatma.myapplication I/﹕ 0
    02-15 19:10:58.917  21554-21591/com.example.fatma.myapplication D/---Networking﹕ Resolving service...
    02-15 19:10:58.934  21554-21554/com.example.fatma.myapplication I/﹕ appName=com.example.fatma.myapplication, acAppName=com.android.cts.openglperf
    02-15 19:10:58.934  21554-21554/com.example.fatma.myapplication I/﹕ 0
    02-15 19:10:58.934  21554-21554/com.example.fatma.myapplication I/﹕ appName=com.example.fatma.myapplication, acAppName=com.android.browser
    02-15 19:10:58.934  21554-21554/com.example.fatma.myapplication I/﹕ 0
    02-15 19:10:58.960  21554-21554/com.example.fatma.myapplication I/﹕ [Mali]surface->num_buffers=4, surface->num_frames=3, win_min_undequeued=1
    02-15 19:10:58.960  21554-21554/com.example.fatma.myapplication I/﹕ [Mali]max_allowed_dequeued_buffers=3
    02-15 19:10:58.983  21554-21554/com.example.fatma.myapplication D/OpenGLRenderer﹕ Enabling debug mode 0
    02-15 19:10:59.318  21554-21554/com.example.fatma.myapplication D/OpenGLRenderer﹕ PatchDescription: bitmapWidth=24.00, bitmapWidth=24.00, pixelWidth=480.00, pixelHeight=24.00, width=2, height=2, quadCnt=6, transQuadCnt=3, colorKey=56
    02-15 19:10:59.318  21554-21554/com.example.fatma.myapplication D/OpenGLRenderer﹕ patch: bitmapWidth=24.00, bitmapHeight=24.00, left=0.00, top=0.00, right=480.00, bottom=24.00, verticesCount=18
    02-15 19:10:59.726  21554-21591/com.example.fatma.myapplication D/---Networking﹕ Service name: NsdChat (3)
    02-15 19:10:59.726  21554-21591/com.example.fatma.myapplication D/---Networking﹕ Port number: 38911
    02-15 19:10:59.980  21554-21591/com.example.fatma.myapplication D/---Networking﹕ Service discovery success: name: NsdChat (3)type: _http._tcp.host: nullport: 0txtRecord: null
    02-15 19:10:59.980  21554-21591/com.example.fatma.myapplication D/---Networking﹕ Same machine: NsdChat (3)
    02-15 19:10:59.980  21554-21591/com.example.fatma.myapplication D/---Networking﹕ Service discovery success: name: NsdChat (3)type: _http._tcp.host: nullport: 0txtRecord: null
    02-15 19:10:59.980  21554-21591/com.example.fatma.myapplication D/---Networking﹕ Same machine: NsdChat (3)

请帮帮我

检查WiFi的方法是:

public boolean isWifiAvailable(Context context){

    boolean wifiConnected = false;

    ConnectivityManager connMgr =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();

    if (activeInfo != null && activeInfo.isConnected()) {
        wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;            
    } else {
        wifiConnected = false;
    }

    return wifiConnected;
}

从任何 ActivityService 调用此方法,如下所示:

isWifiAvailable(this)

其中 thisContext,它将 return truefalse。希望这会有所帮助:)