Search code examples
javaandroidandroid-serviceandroid-broadcastandroid-broadcastreceiver

Programmatically Register For BOOT_COMPLETED Broadcast


I am trying to register my service to startup when the phone boots.

I have setup a BOOT_COMPLETED BroadcastReciever in my service class:

public int onStartCommand(Intent intent, int flags, int startId)
{
    startService(intent);

    _bootCompletedReciever = new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            Log.d(TAG, "Got boot completed");
        }
    };


    IntentFilter filter = new IntentFilter("android.intent.action.BOOT_COMPLETED");
    registerReceiver(_bootCompletedReciever, filter);

    return START_NOT_STICKY;
}

However it is not getting called. I have the permission set in my manifest:

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

Do you know what I am missing in getting this broadcast to fire in my service when the phone boots (without registering for the broadcast in the manifest)?

Answer

I had to use XML in this case to register a class that calls my service on boot:

public class BootBroadcastReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        Intent service = new Intent(context, S_GPS.class);
        context.startService(service);
    }
}

And in the manifest:

<receiver android:name=".BroadcastReceivers.BootBroadcastReceiver" android:enabled="true" android:exported="false">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
    </intent-filter>
</receiver>

Solution

  • Who will start your service on boot up so that onstartcommand() would get called.?
    That will not work. You have to register a receiver statically in manifest and do what you want in onReceive () of receiver.

    Please take a look at this post.