Skip to content

Instantly share code, notes, and snippets.

@grote
Created November 4, 2021 12:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grote/221064c7b3993e6e64321558443653e0 to your computer and use it in GitHub Desktop.
Save grote/221064c7b3993e6e64321558443653e0 to your computer and use it in GitHub Desktop.
Simple test app to test mDNS discovery on Android
class MainActivity : AppCompatActivity() {
private val TAG = "TEST"
private val SERVICE_TYPE = "_googlecast._tcp."
private val mServiceName = "_googlecast._tcp."
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
private val nsdManager by lazy { getSystemService(NsdManager::class.java) }
private val discoveryListener = object : NsdManager.DiscoveryListener {
// Called as soon as service discovery begins.
override fun onDiscoveryStarted(regType: String) {
Log.e(TAG, "Service discovery started")
}
override fun onServiceFound(service: NsdServiceInfo) {
// A service was found! Do something with it.
Log.e(TAG, "Service discovery success$service")
when {
service.serviceType != SERVICE_TYPE -> // Service type is the string containing the protocol and
// transport layer for this service.
Log.d(TAG, "Unknown Service Type: ${service.serviceType}")
service.serviceName == mServiceName -> // The name of the service tells the user what they'd be
// connecting to. It could be "Bob's Chat App".
Log.d(TAG, "Same machine: $mServiceName")
// service.serviceName.contains("NsdChat") -> nsdManager.resolveService(service, resolveListener)
}
}
override fun onServiceLost(service: NsdServiceInfo) {
// When the network service is no longer available.
// Internal bookkeeping code goes here.
Log.e(TAG, "service lost: $service")
}
override fun onDiscoveryStopped(serviceType: String) {
Log.e(TAG, "Discovery stopped: $serviceType")
}
override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) {
Log.e(TAG, "Discovery failed: Error code:$errorCode")
nsdManager.stopServiceDiscovery(this)
}
override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) {
Log.e(TAG, "Discovery failed: Error code:$errorCode")
nsdManager.stopServiceDiscovery(this)
}
}
override fun onStart() {
super.onStart()
nsdManager.discoverServices(SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, discoveryListener)
}
override fun onStop() {
super.onStop()
nsdManager.stopServiceDiscovery(discoveryListener);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment