From 5f167512f5b3bd56616f3a37a40daea2b9f2e415 Mon Sep 17 00:00:00 2001 From: Tamim Hossain <132823494+CodeWithTamim@users.noreply.github.com> Date: Tue, 5 Nov 2024 15:55:08 +0600 Subject: [PATCH] Refactor listenForPackageChanges to remove redundant registerReceiver calls (#3872) Refactored the `listenForPackageChanges` function to remove redundant calls to `registerReceiver` by creating a single `IntentFilter` instance. This simplifies the code and improves readability. --- .../kotlin/com/v2ray/ang/extension/_Ext.kt | 31 +++++++++---------- .../com/v2ray/ang/service/QSTileService.kt | 1 - 2 files changed, 15 insertions(+), 17 deletions(-) diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Ext.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Ext.kt index 9aabecef..b6380e2a 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Ext.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Ext.kt @@ -63,28 +63,27 @@ fun String.removeWhiteSpace(): String = replace("\\s+".toRegex(), "") fun String.toLongEx(): Long = toLongOrNull() ?: 0 -fun Context.listenForPackageChanges(onetime: Boolean = true, callback: () -> Unit) = - object : BroadcastReceiver() { +fun Context.listenForPackageChanges(onetime: Boolean = true, callback: () -> Unit) { + val filter = IntentFilter().apply { + addAction(Intent.ACTION_PACKAGE_ADDED) + addAction(Intent.ACTION_PACKAGE_REMOVED) + addDataScheme("package") + } + + val receiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { callback() if (onetime) context.unregisterReceiver(this) } - }.apply { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { - registerReceiver(this, IntentFilter().apply { - addAction(Intent.ACTION_PACKAGE_ADDED) - addAction(Intent.ACTION_PACKAGE_REMOVED) - addDataScheme("package") - }, Context.RECEIVER_EXPORTED) - } else { - registerReceiver(this, IntentFilter().apply { - addAction(Intent.ACTION_PACKAGE_ADDED) - addAction(Intent.ACTION_PACKAGE_REMOVED) - addDataScheme("package") - }) - } } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + registerReceiver(receiver, filter, Context.RECEIVER_EXPORTED) + } else { + registerReceiver(receiver, filter) + } +} + inline fun Bundle.serializable(key: String): T? = when { Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU -> getSerializable(key, T::class.java) else -> @Suppress("DEPRECATION") getSerializable(key) as? T diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/QSTileService.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/QSTileService.kt index 723ee643..8fcc663c 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/QSTileService.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/QSTileService.kt @@ -55,7 +55,6 @@ class QSTileService : TileService() { override fun onStopListening() { super.onStopListening() - unregisterReceiver(mMsgReceive) mMsgReceive = null }