My Application uses a service that is started by a BOOT_COMPLETE BroadcastReceiver, in run i\'m getting an error
my code:
public class projet extends Br
Best way is to first start an IntentService
from BroadcastReceiver.onReceive()
using:
context.StartService(new Intent(context, YourIntentService.class));
Then in the IntentService.onHandleIntent()
:
@Override
protected void onHandleIntent(Intent intent) {
mContext = getApplicationContext();
mContext.bindService(new Intent("com.ServiceToBind.BIND"), yourConnection, Context.BIND_AUTO_CREATE);
}
According to bindService documentation:
Note: this method can not be called from a BroadcastReceiver component. A pattern you can use to communicate from a BroadcastReceiver to a Service is to call startService(Intent) with the arguments containing the command to be sent, with the service calling its stopSelf(int) method when done executing that command.
What I did: (Not sure if it works in all cases) You can create a Service and start that service in your BroadcastReceiver. Inside your service onCreate() method, you can call a method from another class who is in charge of binding. You can pass the context from service to that class and use it like this: ctx.bindService(...)
BroadcastReceiver
s are not allowed to be bound to a Service
as the other answers here have indicated.
A simple solution I used is to forward the Intent
received by the BroadcastReceiver
to the service you originally wanted to bind to, then implement some code in that service's onStartCommand()
method to handle it.
Just simple. Opt 1: I created an empty Activity (non UI, just onCreate() for Bind service) and finish(). In Broadcast > Start Activity with Bundle (if needed). Problem's resolved.
Opt 2: The same way above options but using an Service instead of Activity. Get event Broadcast > Start a new Service > Bind to existing Service you want to bind.
If you know that the Service
is running you can aquire its Binder
with BroadcastReceiver.peekService(Context, Intent)
method (See peekService docs).
But, as it is already said in the other answers, it is not allowed to bind a Service
from within a BroadcastReceiver
.
One should not bind a service from Broadcast receiver. The reason is broadcast receivers are light weight components, where it has to finish its functionality with in not more than 10 seconds maximum. Else android may forcefully kill your receiver. Binding (establishing connection to) a service may take more than 10 seconds in some worst cases, that's why android won't allow it.
Rules for Broadcast Receivers:
Ref taken from developer android