How to perform a task on device boot up and shut down

Recently, I was working on an Android app project which locks the phone until the user fills up a form and also notify the server that the device has been switched off. So, to achieve this I need to perform some task on the device boot up and shut down and to do so, my application should be listening that the device is started or switched off and do some tasks accordingly.

Android has provided a broadcast “android.intent.action.BOOT_COMPLETED” which will be fired when the device gets booted up and “android.intent.action.ACTION_SHUTDOWN” which will be fired on device shut down.

Let us look into the codes and understand how we can use these broadcasts and perform any task as per our requirement.

1. Create a broadcast listener

You need to create a broadcast listener which will be listening to the BOOT_COMPLETED and ACTION_SHUTDOWN broadcast. The below-provided codes suggest how to do that.

So, you can see in the above code segment that I have created a Broadcast receiver which checks the broadcast action and performs the tasks accordingly. You can add as many checks as you want and perform different tasks on different actions.

2. Register the broadcast listener

Now that we have created the broadcast listener, we would have to register it to listen to the broadcast fired by the system and perform a task on device boot up. We will do that in our AndroidManifest.xml file.

i) We will add the permission so that our application will be allowed to listen to these broadcasts.

ii) Add the broadcast listener using the receiver tag inside the application tag.

You will notice that we have added some other broadcasts as well. This receiver will be triggered on all of this broadcasts.

 

After this, you will be able to receive the broadcasts in your app. But there are a few points that need to carefully note.

  1. You need to open your application manually once after the new installation. So that the app can register the listeners.
  2. Some times the broadcast will not be received by your app because of battery optimization or a startup manager. You need to exclude your application from these for a properly working app.

Hope this has helped you in getting the idea of what exactly happening.

That’s all for this blog. Thank you very much. This is Vedesh Kumar signing off.

. . .

Comment

Add Your Comment

Be the first to comment.

css.php
Hire Us!
Brief us about your requirements and we'll get back to you.
Woo! Hooy!
We have just recieved your project brief and our expert will contact you shortly.
Send Again
Close