Android中的JmDNS UDP发现

时间:2013-08-06 07:44:24

标签: android udp android-service jmdns

我正在进行网络发现演示,我想发现运行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)是否可以使用Android设备搜索udp服务? 3)关于这个还有其他例子吗?

0 个答案:

没有答案