android MDNSBrowseHandler示例代码
时间: 2023-08-19 20:05:08 浏览: 167
以下是使用MDNSBrowseHandler的Android示例代码:
```java
import android.net.nsd.NsdManager;
import android.net.nsd.NsdServiceInfo;
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private static final String SERVICE_TYPE = "_http._tcp.";
private NsdManager.DiscoveryListener mDiscoveryListener;
private NsdManager mNsdManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNsdManager = (NsdManager) getSystemService(NSD_SERVICE);
mDiscoveryListener = new NsdManager.DiscoveryListener() {
@Override
public void onStartDiscoveryFailed(String serviceType, int errorCode) {
Log.e(TAG, "onStartDiscoveryFailed: " + errorCode);
}
@Override
public void onStopDiscoveryFailed(String serviceType, int errorCode) {
Log.e(TAG, "onStopDiscoveryFailed: " + errorCode);
}
@Override
public void onDiscoveryStarted(String serviceType) {
Log.d(TAG, "onDiscoveryStarted: " + serviceType);
}
@Override
public void onDiscoveryStopped(String serviceType) {
Log.d(TAG, "onDiscoveryStopped: " + serviceType);
}
@Override
public void onServiceFound(NsdServiceInfo serviceInfo) {
Log.d(TAG, "onServiceFound: " + serviceInfo.getServiceName());
// Resolve the service to get the IP address and port
mNsdManager.resolveService(serviceInfo, new NsdManager.ResolveListener() {
@Override
public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) {
Log.e(TAG, "onResolveFailed: " + errorCode);
}
@Override
public void onServiceResolved(NsdServiceInfo serviceInfo) {
Log.d(TAG, "onServiceResolved: " + serviceInfo.getHost() + ":" + serviceInfo.getPort());
}
});
}
@Override
public void onServiceLost(NsdServiceInfo serviceInfo) {
Log.d(TAG, "onServiceLost: " + serviceInfo.getServiceName());
}
};
mNsdManager.discoverServices(SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);
}
@Override
protected void onDestroy() {
super.onDestroy();
mNsdManager.stopServiceDiscovery(mDiscoveryListener);
}
}
```
这个示例代码使用Android提供的NsdManager类来发现局域网内的HTTP服务。在这个示例中,我们创建了一个`DiscoveryListener`实例,它实现了`onStartDiscoveryFailed`、`onStopDiscoveryFailed`、`onDiscoveryStarted`、`onDiscoveryStopped`、`onServiceFound`和`onServiceLost`方法,在服务被发现、丢失、启动和停止时调用。然后我们使用`NsdManager`的`discoverServices`方法来发现服务,并传入定义的`DiscoveryListener`实例。最后,在`onServiceFound`方法中,我们调用`resolveService`方法来解析服务,获取它的IP地址和端口号。
阅读全文