Edit AndroidManifest.xml
<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>
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.