Using on boot and on shutdown broadcasts

Sometimes, it's crucial for services to run as the application starts. Also, sometimes it is important to do some cleanup work before we terminate it. In the following example, we will extend the Journaler application to listen for these broadcast messages and do some work. First thing that we will do is create two classes that extend the BroadcastReceiver class:

  • BootReceiver: This is to handle the system boot event
  • ShutdownReceiver: This is to handle the system shutdown event

Register them in your manifest file as follows:

    <manifest  
     ... 
    > 
    ... 
    <receiver 
        android:name=".receiver.BootReceiver" 
        android:enabled="true" 
        android:exported="false"> 
        <intent-filter> 
          <action android:name= "android.intent.action.BOOT_COMPLETED" ...

Get Mastering Android Development with Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.