How to register for ACTION_PACKAGE_ADDED and ACTION_PACKAGE_REMOVED on Android Oreo?

前端 未结 2 1685
南笙
南笙 2020-12-10 17:13

Looking at the latest Android Oreo release notes, it seems like only a handful of implicit broadcasts can be registered by the apps. ACTION_PACKAGE_ADDED and ACTION_PACKAGE_

2条回答
  •  天涯浪人
    2020-12-10 17:53

    As posted in https://stackoverflow.com/a/55819091/1848826

    I could make it work with the following code

    class KotlinBroadcastReceiver(action: (context: Context, intent: Intent) -> Unit) : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) = action(context, intent)
    }
    
    class MainActivity : AppCompatActivity() {
        private val broadcastReceiver = KotlinBroadcastReceiver { context, _ ->
            Toast.makeText(context, "It works", Toast.LENGTH_LONG).show()
        }
    
        override fun onCreate(savedInstanceState: Bundle?) {
            registerReceiver(broadcastReceiver, IntentFilter().apply {
                addAction(Intent.ACTION_PACKAGE_ADDED)
                addAction(Intent.ACTION_PACKAGE_REMOVED)
                addDataScheme("package") // I could not find a constant for that :(
            })
        }
    
        override fun onDestroy() {
            super.onDestroy()
            unregisterReceiver(broadcastReceiver)
        }
    }
    

提交回复
热议问题