要在Android項(xiàng)目中啟用MDNSD功能,您可以通過(guò)以下步驟實(shí)現(xiàn):
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
implementation 'org.apache.httpcomponents:httpclient-android:4.3.5.1'
implementation 'javax.jmdns:jmdns:3.5.6'
import javax.jmdns.JmDNS;
import javax.jmdns.ServiceInfo;
public class MDNSService {
private JmDNS jmdns;
public void registerService(String serviceName, int port) {
try {
jmdns = JmDNS.create();
ServiceInfo serviceInfo = ServiceInfo.create("_http._tcp.local.", serviceName, port, "My MDNS service");
jmdns.registerService(serviceInfo);
} catch (IOException e) {
e.printStackTrace();
}
}
public void discoverServices(String serviceType) {
try {
jmdns = JmDNS.create();
jmdns.addServiceListener(serviceType, new ServiceListener() {
@Override
public void serviceAdded(ServiceEvent event) {
// Service added event
}
@Override
public void serviceRemoved(ServiceEvent event) {
// Service removed event
}
@Override
public void serviceResolved(ServiceEvent event) {
// Service resolved event
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
MDNSService mDNSService = new MDNSService();
mDNSService.registerService("MyService", 8080);
mDNSService.discoverServices("_http._tcp.local.");
通過(guò)以上步驟,您可以在Android項(xiàng)目中啟用MDNSD功能,并實(shí)現(xiàn)服務(wù)的注冊(cè)和發(fā)現(xiàn)。