Android Programatically/Manually Enable or Disable BOOT_COMPLETED BroadcastReceiver

May 9, 2019

When you declared a receiver, it is enabled by default.

<manifest ..>

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

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

You can disable it (and opt to enable it manually by code when necessary, e.g. only when user opt for a reminder)

<receiver android:name=".lib.receiver.BootReceiver" enabled="false">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver

Enable receiver by code.

class BootReceiver : BroadcastReceiver() {    companion object {        fun enable(context: Context) {            val receiver = ComponentName(context, BroadcastReceiver::class.java)            context.packageManager.setComponentEnabledSetting(                receiver,                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,                PackageManager.DONT_KILL_APP            )        }        fun disable(context: Context) {            val receiver = ComponentName(context, BroadcastReceiver::class.java)            context.packageManager.setComponentEnabledSetting(                receiver,                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,                PackageManager.DONT_KILL_APP            )        }    }    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        }    }}
BootReceiver.enable(context)

References:

❤️ 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.