ACTION_PACKAGE_REMOVED 和 ACTION_PACKAGE_INSTALLED 广播未接收到

问题描述 投票:0回答:1

我已经创建了广播接收器文件,并将其添加到清单中,但在删除或安装应用程序时仍然没有收到任何日志

AppChangesReceiver.kt

class AppChangesReceiver : BroadcastReceiver() {

    companion object {
        private const val TAG = "PackageChangeReceiver"
    }

    override fun onReceive(context: Context, intent: Intent) {
        Log.d(TAG,"Received Broadcast")
        val action = intent.action

        action?.let {
            when (it) {
                Intent.ACTION_PACKAGE_REMOVED -> {
                    val removedPackage = intent.data?.encodedSchemeSpecificPart
                    Log.d(TAG, "Package removed: $removedPackage")
                    Toast.makeText(context, "Package removed: $removedPackage", Toast.LENGTH_LONG).show()
                }
            }
        }
    }
}

清单.xml

 <receiver android:name=".AppChangesReceiver"
            android:exported="true"
            tools:ignore="ExportedReceiver">
            <intent-filter>
                <action android:name="android.intent.action.PACKAGE_REMOVED" />
                <action android:name="android.intent.action.PACKAGE_INSTALL" />
                <data android:scheme="package" />
            </intent-filter>
        </receiver>

我希望捕获从应用程序删除或安装应用程序的事件

android performance kotlin broadcastreceiver
1个回答
0
投票

正如评论中提到的,您需要注册此接收器。您不需要清单部分,因此将其删除。下面的代码向您展示了如何注册接收器。您可能想在服务或活动中注册它。

private var receiver = AppChangesReceiver()
IntentFilter().apply {
    addDataScheme("package")
    addAction(Intent.ACTION_PACKAGE_ADDED)
    addAction(Intent.ACTION_PACKAGE_REPLACED)
}.also {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        applicationContext.registerReceiver(receiver, it, RECEIVER_NOT_EXPORTED)
    } else {
        applicationContext.registerReceiver(receiver, it)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.