1 /* 2 * Copyright 2023 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.example.testadvertiseservice 17 18 import android.net.nsd.NsdManager 19 import android.net.nsd.NsdServiceInfo 20 import androidx.appcompat.app.AppCompatActivity 21 import android.os.Bundle 22 import android.text.TextUtils 23 import android.util.Log 24 import android.widget.TextView 25 26 private val TAG = AdvertiseActivity::class.simpleName 27 28 class AdvertiseActivity : AppCompatActivity() { 29 <lambda>null30 private val nsdManager by lazy { getSystemService(NsdManager::class.java) } <lambda>null31 private val lblLog by lazy { findViewById<TextView>(R.id.lblMainActivity) } 32 private val log = mutableListOf<String>() 33 private var listener: RegistrationListener? = null 34 onCreatenull35 override fun onCreate(savedInstanceState: Bundle?) { 36 super.onCreate(savedInstanceState) 37 setContentView(R.layout.activity_main) 38 } 39 onStartnull40 override fun onStart() { 41 super.onStart() 42 43 val service = NsdServiceInfo().apply { 44 serviceName = "test_service" 45 serviceType = "_nmt._tcp" 46 port = 10234 47 } 48 49 listener = RegistrationListener() 50 log("Registering service") 51 nsdManager.registerService(service, NsdManager.PROTOCOL_DNS_SD, listener) 52 } 53 onStopnull54 override fun onStop() { 55 super.onStop() 56 57 listener?.let { nsdManager.unregisterService(it) } 58 listener = null 59 } 60 lognull61 private fun log(msg: String) { 62 runOnUiThread { 63 log.add(msg) 64 Log.i(TAG, msg) 65 lblLog.text = TextUtils.join("\n", log) 66 } 67 } 68 69 inner class RegistrationListener : NsdManager.RegistrationListener { onRegistrationFailednull70 override fun onRegistrationFailed(serviceType: NsdServiceInfo?, errorCode: Int) { 71 log("Registration failed for type $serviceType, error $errorCode") 72 } 73 onUnregistrationFailednull74 override fun onUnregistrationFailed(serviceType: NsdServiceInfo?, errorCode: Int) { 75 log("Unregistration failed for type $serviceType, error $errorCode") 76 } 77 onServiceRegisterednull78 override fun onServiceRegistered(serviceInfo: NsdServiceInfo?) { 79 log("Service registered for type $serviceInfo") 80 } 81 onServiceUnregisterednull82 override fun onServiceUnregistered(serviceType: NsdServiceInfo?) { 83 log("Service unregistered for type $serviceType") 84 } 85 } 86 }