1

我正在做一个网络发现演示,我想在其中发现运行 udp 服务的机器。(连接到单个 wifi)。我正在使用以下代码

public class DnssdDiscovery extends Activity {

    android.net.wifi.WifiManager.MulticastLock lock;
    android.os.Handler handler = new android.os.Handler();

    ListView mListView;
    ArrayList<String> new_conn_list;

    DeviceListCustomAdapter new_conn_adapter;

    ProgressDialog pbdnssd = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);

        mListView = (ListView) findViewById(R.id.listView);

        new_conn_list = new ArrayList<String>();

        new_conn_adapter = new DeviceListCustomAdapter(getApplicationContext(),
                new_conn_list);
        mListView.setAdapter(new_conn_adapter);

        pbdnssd = new ProgressDialog(DnssdDiscovery.this);
        pbdnssd.setCanceledOnTouchOutside(false);
        pbdnssd.setMessage("Loading...");

       /* handler.postDelayed(new Runnable() {
            public void run() {
                setUp();
            }
            }, 1000);*/

    }    /** Called when the activity is first created. */


    private String type = "_Controller._udp.local.";
    private JmDNS jmdns = null;
    private ServiceListener listener = null;
    private ServiceInfo serviceInfo;

    @SuppressLint("NewApi")
    private void setUp() {
        android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) getSystemService(android.content.Context.WIFI_SERVICE);
        lock = wifi.createMulticastLock("mylockthereturn");
        lock.setReferenceCounted(true);
        lock.acquire();
        try {
            jmdns = JmDNS.create();
            jmdns.addServiceListener(type, listener = new ServiceListener() {

                @Override
                public void serviceResolved(ServiceEvent ev) {
                    notifyUser(ev.getInfo().getName().toString() );
                }

                @Override
                public void serviceRemoved(ServiceEvent ev) {
                    //notifyUser("Service removed: " + ev.getName());
                }

                @Override
                public void serviceAdded(ServiceEvent event) {
                    // Required to force serviceResolved to be called again (after the first search)
                    jmdns.requestServiceInfo(event.getType(), event.getName(), 1);
                }
            });
            serviceInfo = ServiceInfo.create("_Controller._udp.local.", "AndroidTest", 65534, "plain test service from android");
            jmdns.registerService(serviceInfo);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
    }

    public void clickDiscover(View v) {
        if (isConnectingToInternet()) {
            /*handler.postDelayed(new Runnable() {
                    public void run() {
                        setUp();
                    }
                    }, 1000);*/
            if (!pbdnssd.isShowing())
                pbdnssd.show();
            new_conn_adapter.clearAll();
            handler.postDelayed(new Runnable() {
                public void run() {
                    setUp();
                }
            }, 1000);
            v.setEnabled(false);
            ((Button) findViewById(R.id.stop_btn)).setEnabled(true);
        }else {
            Toast.makeText(getApplicationContext(), "Network Error",
                    Toast.LENGTH_SHORT).show();
        }
    }

    @SuppressLint("NewApi")
    public void clickStop(View v){
        ((Button) findViewById(R.id.discover_btn)).setEnabled(true);
        if (jmdns != null) {
            if (listener != null) {
                jmdns.removeServiceListener(type, listener);
                listener = null;
            }
            jmdns.unregisterAllServices();
            try {
                jmdns.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            jmdns = null;
        }
        //repo.stop();
        //s.stop();
        try {
            lock.release();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private void notifyUser(final String msg) {
        handler.postDelayed(new Runnable() {
            public void run() {
                String itemName = msg;
                new_conn_adapter.add(itemName);
                new_conn_adapter.notifyDataSetChanged();
                if(pbdnssd.isShowing())
                    pbdnssd.dismiss();
            }
        }, 1);

    }

    @Override
    protected void onStart() {
    super.onStart();
    //new Thread(){public void run() {setUp();}}.start();
}

    @SuppressLint("NewApi")
    @Override
    protected void onStop() {
        if (jmdns != null) {
            if (listener != null) {
                jmdns.removeServiceListener(type, listener);
                listener = null;
            }
            jmdns.unregisterAllServices();
            try {
                jmdns.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            jmdns = null;
        }
        //repo.stop();
        //s.stop();
        try {
            lock.release();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        super.onStop();
    }

    public boolean isConnectingToInternet() {
        ConnectivityManager connectivity = (ConnectivityManager) getApplicationContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }

        }
        return false;
    }

}

主要是我不确定我使用的服务类型是否正确。1)UDP服务的服务类型是什么?2) 是否可以使用安卓设备搜索 udp 服务?3)还有其他关于这个的例子吗?

4

0 回答 0