Android Execute Code on Device Startup/Bootup

May 9, 2019
android.intent.action.BOOT_COMPLETED with BroadcastReceiver

Edit AndroidManifest.xml

<manifest ..>

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

    <application ...>
        <receiver android:name=".lib.receiver.BootReceiver">
                <action android:name="android.intent.action.BOOT_COMPLETED" />

NOTE: You might need <action android:name="android.intent.action.QUICKBOOT_POWERON" /> as well for certain devices (e.g. HTC).

.lib.receiver.BootReceiver Code

class BootReceiver : BroadcastReceiver() {    override fun onReceive(context: Context, intent: Intent) {        Timber.d("onReceive=${intent.action}")        // if (intent.action == "android.intent.action.BOOT_COMPLETED") {        if (intent.action == Intent.ACTION_BOOT_COMPLETED) {            // do something, start an alarm perhaps        }    }}

NOTE: The BootReceiver is enabled by default. You can opt to disable it by default and enable it when necessary.

NOTE: Certain phone have extra software which block non-authorized app from receiving bootup/autostart event. For Xiaomi, you need to access Security app, click Manage apps, then search for and click on you app, under Security enable Autostart option.

NOTE: Don't depend on BootReceiver to always work on all devices. If you are using AlarmManager, it is advisable to start/set the alarm during app startup as well.

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.