Search code examples
androidkotlinbroadcastreceiverintentfilterandroid-broadcast

BroadcastReceiver Intent.ACTION_PACKAGE_ADDED/REMOVED Android Oreo


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.


Solution

  • 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