当前位置: 首页 > 工具软件 > JmDNS > 使用案例 >

未发现android设备,Android – jmdns没有发现设备

姬宝
2023-12-01

我是Android的ZeroConf Browser的作者,我使用开源库JmDNS进行所有解析.它工作得很好,但有一些技巧可以让它正常工作.

>在Android manifest.xml中,确保至少拥有这些权限.

>在开始活动之前,您必须通过获取多播锁来允许多播数据包.

@Override

protected void onStart() {

Log.i(TAG, "Starting ServiceActivity...");

super.onStart();

try {

Log.i(TAG, "Starting Mutlicast Lock...");

WifiManager wifi = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);

// get the device ip address

final InetAddress deviceIpAddress = getDeviceIpAddress(wifi);

multicastLock = wifi.createMulticastLock(getClass().getName());

multicastLock.setReferenceCounted(true);

multicastLock.acquire();

Log.i(TAG, "Starting ZeroConf probe....");

jmdns = JmDNS.create(deviceIpAddress, HOSTNAME);

jmdns.addServiceTypeListener(this);

} catch (IOException ex) {

Log.e(TAG, ex.getMessage(), ex);

}

Log.i(TAG, "Started ZeroConf probe....");

}

private InetAddress getDeviceIpAddress(WifiManager wifi) {

InetAddress result = null;

try {

// default to Android localhost

result = InetAddress.getByName("10.0.0.2");

// figure out our wifi address, otherwise bail

WifiInfo wifiinfo = wifi.getConnectionInfo();

int intaddr = wifiinfo.getIpAddress();

byte[] byteaddr = new byte[] { (byte) (intaddr & 0xff), (byte) (intaddr >> 8 & 0xff),

(byte) (intaddr >> 16 & 0xff), (byte) (intaddr >> 24 & 0xff) };

result = InetAddress.getByAddress(byteaddr);

} catch (UnknownHostException ex) {

Log.w(TAG, String.format("getDeviceIpAddress Error: %s", ex.getMessage()));

}

return result;

}

>不要忘记停止扫描以解锁多播锁并关闭JmDNS.

@Override

protected void onStop() {

Log.i(TAG, "Stopping ServiceActivity...");

super.onStop();

stopScan();

}

private static void stopScan() {

try {

if (jmdns != null) {

Log.i(TAG, "Stopping ZeroConf probe....");

jmdns.unregisterAllServices();

jmdns.close();

jmdns = null;

}

if (multicastLock != null) {

Log.i(TAG, "Releasing Mutlicast Lock...");

multicastLock.release();

multicastLock = null;

}

} catch (Exception ex) {

Log.e(TAG, ex.getMessage(), ex);

}

}

>最重要的是不要使用默认构造函数.您必须使用IP地址构造函数.我注意到你的代码中只是在做JmDNS.create().我认为由于某种原因,它在Android上运行的唯一方法是使用下面的构造函数.

jmdns = JmDNS.create(deviceIpAddress, HOSTNAME);

 类似资料: