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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.