我是Android瀏覽器的作者,我使用開源庫JmDNS來解決我的所有問題。 它工作得不錯,但是有一些技巧讓它正常工作。
在你的Android manifest.xml 中,確保你至少擁有這些許可權。
在啟動 Activity 之前,必須通過獲取多播鎖來允許多個。@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);
}
}
大多數importanty不使用默認構造函數。 你必須使用IP地址構造函數。 我注意到你的代碼只是在做 JmDNS.create() 。 我認為在安卓上使用contructor的唯一方法是使用下面的。jmdns = JmDNS.create(deviceIpAddress, HOSTNAME);