Ich hab den Quellcode mal sauber rausgeschrieben. Orientiert habe ich mich hier.
Die Antwortzeit beträgt zwischen Start der Discovery und Found eines Services bis zu 40 Sekunden.
Java: MainActivity.java
public class MainActivity extends AppCompatActivity {
NsdManager mNsdManager;
NsdManager.DiscoveryListener mDiscoveryListener;
public static final String SERVICE_TYPE = "_services._dns-sd._udp.";
public static final String TAG = "NsdHelper";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onStart() {
super.onStart();
mNsdManager = (NsdManager) this.getSystemService(Context.NSD_SERVICE);
discoverServices();
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
void initDiscoveryListener(){
mDiscoveryListener = new NsdManager.DiscoveryListener() {
@Override
public void onStartDiscoveryFailed(String serviceType, int errorCode) {
Log.e(TAG, "Discovery START failed: Error code:" + errorCode);
}
@Override
public void onStopDiscoveryFailed(String serviceType, int errorCode) {
Log.e(TAG, "Discovery STOP failed: Error code:" + errorCode);
}
@Override
public void onDiscoveryStarted(String serviceType) {
Log.d(TAG, "Service discovery started");
}
@Override
public void onDiscoveryStopped(String serviceType) {
Log.i(TAG, "Discovery stopped: " + serviceType);
}
@Override
public void onServiceFound(NsdServiceInfo serviceInfo) {
Log.d(TAG, "Service discovery success" + serviceInfo);
}
@Override
public void onServiceLost(NsdServiceInfo serviceInfo) {
Log.e(TAG, "service lost" + serviceInfo);
}
};
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void discoverServices() {
stopDiscovery(); // Cancel any existing discovery request
initDiscoveryListener();
mNsdManager.discoverServices(
SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void stopDiscovery() {
if (mDiscoveryListener != null) {
try {
mNsdManager.stopServiceDiscovery(mDiscoveryListener);
} finally {
}
mDiscoveryListener = null;
}
}
}
Alles anzeigen