Android NSD代码报错:initializeRegistrationListener()需添加分号
Hey there! Let's work through this issue together—first fixing that syntax error, then making sure your MDNS service discovery works smoothly.
1. Fixing the "Missing Semicolon" Error on initializeRegistrationListener()
That error usually doesn't mean you need a semicolon on that line—it's a side effect of a problem elsewhere in your code. Here are the most common fixes:
Check if the method is nested inside another method
Java doesn't allow methods to be defined inside other methods. If you pastedpublic void initializeRegistrationListener()insideonCreate()or another function, the compiler will treat it as invalid syntax and ask for a semicolon (since it expects a statement, not a method declaration). Move this method to be a direct member of your activity/fragment class (at the same level asonCreate()).Verify code before this method is properly closed
Look at the code right aboveinitializeRegistrationListener()—did you forget a closing}for an if statement, loop, or previous code block? If the compiler thinks you're still inside a code block, it'll misinterpret the method declaration as a broken statement and demand a semicolon.Double-check the method declaration syntax
Make sure the line ends with{(not a semicolon or comma). For example:// Correct public void initializeRegistrationListener() { // Your listener code here } // Incorrect (would trigger the error) public void initializeRegistrationListener(); { // ... }
2. Getting MDNS Service Discovery Working
Once the syntax error is fixed, let's ensure your Android device can find your custom MDNS service. Here are key steps:
a. Add Required Permissions
In your AndroidManifest.xml, add these permissions to enable network access and multicast (critical for MDNS):
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
b. Use the Correct Service Type
Make sure the service type you pass to discoverServices() matches exactly what your MDNS service uses. For example, if your service is a TCP-based HTTP service, it'll look like _http._tcp.local.—replace this with your service's specific type.
c. Example Working Code Structure
Here's a clean, complete example to reference (adjust the service type and name to match your MDNS service):
public class DiscoveryActivity extends AppCompatActivity { private NsdManager mNsdManager; private NsdManager.DiscoveryListener mDiscoveryListener; // Replace with your MDNS service type private static final String TARGET_SERVICE_TYPE = "_my-custom-service._tcp.local."; // Replace with your MDNS service name private static final String TARGET_SERVICE_NAME = "MyMDNSService"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_discovery); mNsdManager = (NsdManager) getSystemService(Context.NSD_SERVICE); initializeDiscoveryListener(); // Start looking for services mNsdManager.discoverServices(TARGET_SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener); } // This is a top-level class method (not nested!) private void initializeDiscoveryListener() { mDiscoveryListener = new NsdManager.DiscoveryListener() { @Override public void onDiscoveryStarted(String regType) { Log.d("NSD", "Discovery started for type: " + regType); } @Override public void onServiceFound(NsdServiceInfo serviceInfo) { Log.d("NSD", "Found service: " + serviceInfo.getServiceName()); // Check if this is the service we're looking for if (serviceInfo.getServiceName().equals(TARGET_SERVICE_NAME)) { // Resolve the service to get its IP and port mNsdManager.resolveService(serviceInfo, new NsdManager.ResolveListener() { @Override public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) { Log.e("NSD", "Resolve failed: " + errorCode); } @Override public void onServiceResolved(NsdServiceInfo serviceInfo) { // Success! Get connection details InetAddress serviceHost = serviceInfo.getHost(); int servicePort = serviceInfo.getPort(); Log.d("NSD", "Resolved service: " + serviceHost + ":" + servicePort); // Now you can connect to this service } }); } } @Override public void onServiceLost(NsdServiceInfo serviceInfo) { Log.d("NSD", "Lost service: " + serviceInfo.getServiceName()); } @Override public void onDiscoveryStopped(String serviceType) { Log.d("NSD", "Discovery stopped"); } @Override public void onStartDiscoveryFailed(String serviceType, int errorCode) { Log.e("NSD", "Start discovery failed: " + errorCode); mNsdManager.stopServiceDiscovery(this); } @Override public void onStopDiscoveryFailed(String serviceType, int errorCode) { Log.e("NSD", "Stop discovery failed: " + errorCode); mNsdManager.stopServiceDiscovery(this); } }; } @Override protected void onPause() { super.onPause(); // Stop discovery when the app is paused to save resources if (mNsdManager != null && mDiscoveryListener != null) { try { mNsdManager.stopServiceDiscovery(mDiscoveryListener); } catch (IllegalArgumentException e) { e.printStackTrace(); } } } @Override protected void onDestroy() { super.onDestroy(); mDiscoveryListener = null; mNsdManager = null; } }
d. Additional Checks
- Ensure your Android device and the MDNS service are on the same WiFi network (MDNS works locally only).
- Verify your custom MDNS service is running and advertising correctly—you can use tools like
dns-sd(on macOS/Linux) or MDNS scanners to confirm it's visible on the network.
内容的提问来源于stack exchange,提问作者Salem Masoud

