要在Android項目中啟用MDNSD功能,您可以通過以下步驟實現:
<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.");
通過以上步驟,您可以在Android項目中啟用MDNSD功能,并實現服務的注冊和發現。