Use ?.let instead if-null-test, avoid runnable

This commit is contained in:
Fabian Wiesel
2024-02-26 19:40:57 +01:00
parent fa6e4da2c5
commit 58095bc67b
5 changed files with 44 additions and 55 deletions

View File

@@ -91,10 +91,10 @@ class DiscoverActivity : Activity() {
override fun onDestroy() { override fun onDestroy() {
Log.i(TAG, "ChildMonitoring stop") Log.i(TAG, "ChildMonitoring stop")
if (this.discoveryListener != null) { this.discoveryListener?.let {
Log.i(TAG, "Unregistering monitoring service")
this.nsdManager!!.stopServiceDiscovery(discoveryListener)
this.discoveryListener = null this.discoveryListener = null
Log.i(TAG, "Unregistering monitoring service")
this.nsdManager!!.stopServiceDiscovery(it)
} }
super.onDestroy() super.onDestroy()
} }
@@ -102,17 +102,14 @@ class DiscoverActivity : Activity() {
private fun startServiceDiscovery(serviceType: String) { private fun startServiceDiscovery(serviceType: String) {
val nsdManager = this.getSystemService(NSD_SERVICE) as NsdManager val nsdManager = this.getSystemService(NSD_SERVICE) as NsdManager
val wifi = this.applicationContext.getSystemService(WIFI_SERVICE) as WifiManager val wifi = this.applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
val multicastReleaser: Runnable val multicastLock = wifi.createMulticastLock("multicastLock")
multicastReleaser = run { multicastLock.setReferenceCounted(true)
val multicastLock = wifi.createMulticastLock("multicastLock") multicastLock.acquire()
multicastLock.setReferenceCounted(true) val multicastReleaser = {
multicastLock.acquire() try {
Runnable { multicastLock.release()
try { } catch (ignored: Exception) {
multicastLock.release() // don't really care
} catch (ignored: Exception) {
//dont really care
}
} }
} }
val serviceTable = findViewById<ListView>(R.id.ServiceTable) val serviceTable = findViewById<ListView>(R.id.ServiceTable)
@@ -121,9 +118,8 @@ class DiscoverActivity : Activity() {
serviceTable.adapter = availableServicesAdapter serviceTable.adapter = availableServicesAdapter
serviceTable.onItemClickListener = OnItemClickListener { parent: AdapterView<*>, _: View?, position: Int, _: Long -> serviceTable.onItemClickListener = OnItemClickListener { parent: AdapterView<*>, _: View?, position: Int, _: Long ->
val info = parent.getItemAtPosition(position) as ServiceInfoWrapper val info = parent.getItemAtPosition(position) as ServiceInfoWrapper
val address = info.address info.address?.let {
if (address != null) { connectToChild(it, info.port, info.name)
connectToChild(address, info.port, info.name)
} }
} }
@@ -172,24 +168,24 @@ class DiscoverActivity : Activity() {
// When the network service is no longer available. // When the network service is no longer available.
// Internal bookkeeping code goes here. // Internal bookkeeping code goes here.
Log.e(TAG, "Service lost: $service") Log.e(TAG, "Service lost: $service")
multicastReleaser.run() multicastReleaser()
} }
override fun onDiscoveryStopped(serviceType: String) { override fun onDiscoveryStopped(serviceType: String) {
Log.i(TAG, "Discovery stopped: $serviceType") Log.i(TAG, "Discovery stopped: $serviceType")
multicastReleaser.run() multicastReleaser()
} }
override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) { override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) {
Log.e(TAG, "Discovery failed: Error code: $errorCode") Log.e(TAG, "Discovery failed: Error code: $errorCode")
nsdManager.stopServiceDiscovery(this) nsdManager.stopServiceDiscovery(this)
multicastReleaser.run() multicastReleaser()
} }
override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) { override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) {
Log.e(TAG, "Discovery failed: Error code: $errorCode") Log.e(TAG, "Discovery failed: Error code: $errorCode")
nsdManager.stopServiceDiscovery(this) nsdManager.stopServiceDiscovery(this)
multicastReleaser.run() multicastReleaser()
} }
} }
nsdManager.discoverServices( nsdManager.discoverServices(

View File

@@ -65,10 +65,10 @@ class ListenActivity : Activity() {
private fun ensureServiceRunningAndBind(bundle: Bundle?) { private fun ensureServiceRunningAndBind(bundle: Bundle?) {
val context: Context = this val context: Context = this
val intent = Intent(context, ListenService::class.java) val intent = Intent(context, ListenService::class.java)
if (bundle != null) { bundle?.let {
intent.putExtra("name", bundle.getString("name")) intent.putExtra("name", it.getString("name"))
intent.putExtra("address", bundle.getString("address")) intent.putExtra("address", it.getString("address"))
intent.putExtra("port", bundle.getInt("port")) intent.putExtra("port", it.getInt("port"))
ContextCompat.startForegroundService(context, intent) ContextCompat.startForegroundService(context, intent)
} }
// Attempts to establish a connection with the service. We use an // Attempts to establish a connection with the service. We use an

View File

@@ -58,25 +58,23 @@ class ListenService : Service() {
Log.i(TAG, "Received start id $startId: $intent") Log.i(TAG, "Received start id $startId: $intent")
// Display a notification about us starting. We put an icon in the status bar. // Display a notification about us starting. We put an icon in the status bar.
createNotificationChannel() createNotificationChannel()
val extras = intent.extras intent.extras?.let {
if (extras != null) { val name = it.getString("name")
val name = extras.getString("name")
childDeviceName = name childDeviceName = name
val n = buildNotification(name) val n = buildNotification(name)
val foregroundServiceType = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK else 0 // Keep the linter happy val foregroundServiceType = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK else 0 // Keep the linter happy
ServiceCompat.startForeground(this, ID, n, foregroundServiceType) ServiceCompat.startForeground(this, ID, n, foregroundServiceType)
val address = extras.getString("address") val address = it.getString("address")
val port = extras.getInt("port") val port = it.getInt("port")
doListen(address, port) doListen(address, port)
} }
return START_REDELIVER_INTENT return START_REDELIVER_INTENT
} }
override fun onDestroy() { override fun onDestroy() {
val lt = this.listenThread this.listenThread?.let {
if (lt != null) {
lt.interrupt()
this.listenThread = null this.listenThread = null
it.interrupt()
} }
// Cancel the persistent notification. // Cancel the persistent notification.
@@ -121,12 +119,12 @@ class ListenService : Service() {
} }
} }
fun setErrorCallback(errorCallback: Runnable?) { fun setErrorCallback(errorCallback: (() -> Unit)) {
mErrorCallback = errorCallback this.errorCallback = errorCallback
} }
fun setUpdateCallback(updateCallback: Runnable?) { fun setUpdateCallback(updateCallback: (() -> Unit)) {
mUpdateCallback = updateCallback this.updateCallback = updateCallback
} }
inner class ListenBinder : Binder() { inner class ListenBinder : Binder() {
@@ -134,8 +132,8 @@ class ListenService : Service() {
get() = this@ListenService get() = this@ListenService
} }
private var mErrorCallback: Runnable? = null private var errorCallback: (() -> Unit)? = null
private var mUpdateCallback: Runnable? = null private var updateCallback: (() -> Unit)? = null
private fun doListen(address: String?, port: Int) { private fun doListen(address: String?, port: Int) {
val lt = Thread { val lt = Thread {
try { try {
@@ -150,8 +148,7 @@ class ListenService : Service() {
// an alert to notify the user that the connection has been // an alert to notify the user that the connection has been
// interrupted. // interrupted.
playAlert() playAlert()
val errorCallback = mErrorCallback errorCallback?.invoke()
errorCallback?.run()
} }
} }
this.listenThread = lt this.listenThread = lt
@@ -181,8 +178,7 @@ class ListenService : Service() {
val decodedBytes = ShortArray(decoded) val decodedBytes = ShortArray(decoded)
System.arraycopy(decodedBuffer, 0, decodedBytes, 0, decoded) System.arraycopy(decodedBuffer, 0, decodedBytes, 0, decoded)
volumeHistory.onAudioData(decodedBytes) volumeHistory.onAudioData(decodedBytes)
val updateCallback = mUpdateCallback updateCallback?.invoke()
updateCallback?.run()
} }
} }
} catch (e: Exception) { } catch (e: Exception) {

View File

@@ -120,9 +120,9 @@ class MonitorActivity : Activity() {
private fun doUnbindAndStopService() { private fun doUnbindAndStopService() {
if (this.shouldUnbind) { if (this.shouldUnbind) {
this.shouldUnbind = false
// Release information about the service's state. // Release information about the service's state.
unbindService(connection) unbindService(connection)
this.shouldUnbind = false
} }
val context: Context = this val context: Context = this
val intent = Intent(context, MonitorService::class.java) val intent = Intent(context, MonitorService::class.java)

View File

@@ -200,11 +200,10 @@ class MonitorService : Service() {
} }
private fun unregisterService() { private fun unregisterService() {
val currentListener = this.registrationListener this.registrationListener?.let {
if (currentListener != null) {
Log.i(TAG, "Unregistering monitoring service")
this.nsdManager!!.unregisterService(currentListener)
this.registrationListener = null this.registrationListener = null
Log.i(TAG, "Unregistering monitoring service")
this.nsdManager!!.unregisterService(it)
} }
} }
@@ -231,18 +230,16 @@ class MonitorService : Service() {
} }
override fun onDestroy() { override fun onDestroy() {
val mt = this.monitorThread this.monitorThread?.let {
if (mt != null) {
mt.interrupt()
this.monitorThread = null this.monitorThread = null
it.interrupt()
} }
unregisterService() unregisterService()
this.connectionToken = null this.connectionToken = null
val sock = this.currentSocket this.currentSocket?.let {
if (sock != null) { this.currentSocket = null
try { try {
sock.close() it.close()
this.currentSocket = null
} catch (e: IOException) { } catch (e: IOException) {
Log.e(TAG, "Failed to close active socket on port $currentPort") Log.e(TAG, "Failed to close active socket on port $currentPort")
} }