I have a broadcast receiver in my application.
When I receive a broadcast I pass the content to a service to decode it.
public class Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("xxx.yyy.zzz")) {
Log.d("Receiver", "Intent received from server!");
byte[] data = intent.getByteArrayExtra("Data");
String params = intent.getStringExtra("Params");
Intent i = new Intent(context, DecodeService.class);
i.putExtra("Data", data);
i.putExtra("Params", params);
context.startService(i);
}
}
}
Depending on the content, I start an appropriate activity from this service.
Now I have some questions about how to manage this service.
-
Where should I stop this service? Should I stop it after starting an activity from it and start it again when I receive a broadcast? Or should I let it run while the application is active and stop it when the application is exited.
-
What would be the advantage of binding to this service? And can I bind to a service from a broadcastreceiver?
Seems like you are using
Servicejust to decode and start anActivity. Instead, I would suggest you to ditch the service part and try to accommodate decoding and launching your activity from theBroadcastReceiverclass.For simple tasks, dont get involved with services. It will be a lot easier to expect your application’s behavior when not using services.
In case you really want to use service, then I would suggest you to read about IntentService. It is also a type of service which runs in the background, does its job on a separate thread and automatically gets killed at the end.