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>
The receiver you are registering there can't survive a reboot, it's impossible, because it is dynamically registered and the registration is lost at reboot.
What you CAN do, is to register a receiver in the manifest, but set that receiver to DISABLED, use this flag:
android:enabled=["true" | "false"]
Then you can programatically set it to enabled using the package manager
context.getPackageManager()
.setComponentEnabledSetting(ComponentName componentName, int newState, int flags);
From the docs:
componentName The component to enable
newState The new enabled state for the component. The legal values for this state are:
COMPONENT_ENABLED_STATE_ENABLED, COMPONENT_ENABLED_STATE_DISABLED and COMPONENT_ENABLED_STATE_DEFAULT
The last one removes the setting, thereby restoring the component's state to whatever was set in it's manifest (or enabled, by default).
flags Optional behavior flags: DONT_KILL_APP or 0.
See the package manager documentation for more info.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With