BroadcastReceiver Intent.ACTION_PACKAGE_ADDED/REMOVED Android Oreo

穿精又带淫゛_ 提交于 2019-12-24 01:37:09

问题


This is my broadcast receiver class and the implementation of it in main.

Problem is that onReceive method never gets called.

class MyBroadcastReceiver : BroadcastReceiver() {
  override fun onReceive(p0: Context?, p1: Intent?) {
     Toast.makeText(p0, "It works", Toast.LENGTH_LONG).show()
  }
}

class MainActivity : AppCompatActivity() {
     ......

     private var broadcastReceiver: MyBroadcastReceiver = MyBroadcastReceiver()

     override fun onCreate(savedInstanceState: Bundle?) {
            ......

            registerReceiver(broadcastReceiver, IntentFilter().apply {
                addAction(Intent.ACTION_PACKAGE_ADDED)
                addAction(Intent.ACTION_PACKAGE_REMOVED)
            })
     }

     override fun onDestroy() {
            super.onDestroy()
            unregisterReceiver(broadcastReceiver)
     }
 }

Please help. Thanks in advance.


回答1:


Usually the BroadcastReceiver needs a number of steps to be set up.

First of all did yout pass to the manifest the receiver?

<receiver android:name=".MyBroadcastReceiver"  android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
        <action android:name="android.intent.action.INPUT_METHOD_CHANGED" />
    </intent-filter>
</receiver>

Edit: Please see this post, where is suggested ACTION_PACKAGE_FULLY_REMOVED or JobScheduler

try also to reinstall the app on the emulator




回答2:


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)
    }
}


来源:https://stackoverflow.com/questions/51669361/broadcastreceiver-intent-action-package-added-removed-android-oreo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!