Search code examples
androidbroadcastreceiverandroid-manifestintentfilterbootcompleted

boot_completed action to register programmatically and not in manifest


I was trying to register a receiver programmatically for actionandroid.intent.action.BOOT_COMPLETED , i.e Lets take i have reciever class named BootReceiver which extends BroadCastReceiver class.

So in one of my activity class i have written this code,

IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.action.BOOT_COMPLETED");
        intentFilter.addAction("android.intent.action.PACKAGE_REPLACED");

        BootReceiver receiver = new BootReceiver();
        getApplicationContext().registerReceiver(receiver, intentFilter);

I was trying to do both update of app as well boot_completed action to same broadcast receiver.

So what i tried is, I ran the activity with registering of above code and then restarted the device. I was not getting any callback to BootReceiver onReceive() method.

Is it possible to programmatically declare receiver for the boot_completed action or is it necessary to declare receiver in manifest file.

Actually my requirement is to programmatically declare it.

Thanks in advance.


Solution

  • I was trying to register a receiver programmatically for actionandroid.intent.action.BOOT_COMPLETED

    By the time registerReceiver() is called, the boot will have long since happened. The only place to register for android.intent.action.BOOT_COMPLETED is in the manifest, as that is able to register interest in broadcasts even when you do not have a process running.

    Is it possible to programmatically declare receiver for the boot_completed action

    No. You can request it, but it will never work.

    is it necessary to declare receiver in manifest file

    If you want one to work, yes.