如何在Android項(xiàng)目中啟用MDNSD功能

小樊
108
2024-08-22 12:27:29

要在Android項(xiàng)目中啟用MDNSD功能,您可以通過(guò)以下步驟實(shí)現(xiàn):

  1. 在項(xiàng)目的AndroidManifest.xml文件中添加以下權(quá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" />
  1. 在build.gradle文件中添加mDNS庫(kù)的依賴:
implementation 'org.apache.httpcomponents:httpclient-android:4.3.5.1'
implementation 'javax.jmdns:jmdns:3.5.6'
  1. 創(chuàng)建一個(gè)MDNS服務(wù)類,該類將負(fù)責(zé)注冊(cè)服務(wù)和發(fā)現(xiàn)服務(wù)。以下是一個(gè)示例MDNSService類的代碼:
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();
        }
    }
}
  1. 在您的應(yīng)用程序中使用MDNSService類來(lái)注冊(cè)和發(fā)現(xiàn)服務(wù)。例如,在您的Activity中:
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)。

0