Android - passing callback from activity to service - android

I have a situation where an activity needs to start 2 services, one is bound, one is not.
The bound will return a Ibinder to the activity. But the activity needs to some how provide a callback to both the services, i.e. both services must be able to call some methods in a nested class in the activity.
What is the best way to do this ? Should I use broadcast from services, and then call the desired API from the onReceive() ? Or can I pass a IBinder from my activity to service in the intent, and the service could use it to make a IPC call back ?
Edit
Forgot to clarify .. the two services are in a different app than the activity.

you could to use LocalBroadcastManager Sending An Intent for Activity
I believe it is the best option for this scenario EventBus or Otto
EventBus is an Android optimized publish/subscribe event bus. A
typical use case for Android apps is gluing Activities, Fragments, and
background threads together. Conventional wiring of those elements
often introduces complex and error-prone dependencies and life cycle
issues. With EventBus propagating listeners through all participants
(e.g. background service -> activity -> multiple fragments or helper
classes) becomes deprecated. EventBus decouples event senders and
receivers and thus simplifies communication between app components.
Less code, better quality. And you don't need to implement a single
interface!

Related

Bound Service vs Unbound + singleton for communication

I have a service, I need to communicate to with it (one service - many fragments/activities). There are two options for this:
Have a singleton that controls the service - starts it and then binds to it (using the app context)
Have a singleton that controls the service - starts it, the service when ready registers back as a delegate to the singleton (in a WeakReference)
Solution no 2 seems simpler to me, but whenever I read about communication with services there is the concept of the bound service.
Is there any benefit of having a bound service instead of the service registering itself as a delegate (and unregistering with onDestroy)?
Edit 1: The service is to keep the communication alive, it's expensive to set up a new communication channel. Even if no one requested any data it should keep the channel alive (heartbeat).
The service is foreground, it should run even if the activity that requested the data gets killed by the system. The next time it is created the data will be there.
The data requested by one screen might be useful for some other (therefore has to be stored in a singleton).
Bound and unbound services are both usable patterns and you should pick whatever pattern is better for you use case.
You should pick bound service if you want your service to have the same lifecycle as the components that bind to it. If you need an independent service use an unbound version.
The only benefit of one approach versus another is the simplicity of implementation.
In you case, I think you need the service only while there are running activities and fragments, then the easiest way, in my opinion, would be to make a bound service and make every activity bind to it. With that, you'll get a simple communication interface between you activities (and fragments, since they have access to containing activity) and your service.
The benefits of this approach are:
the service will stop itself if all activities unbind and start itself when first activity binds to it.
you won't need to track all running activities in the singleton and manually unbind
you won't need to maintain a singleton manager, less code -> less bugs
sometimes onDestroy can be skipped by the system and you can leak the service with the 2 approach.
Since you need your service to be running the correct option will be to use a started service and make each activity bind to it when needed. It's a common pattern.
Started service will run until you explicitly stop it or it stops itself, you can have a singleton manager that will be responsible for that.
But at the same time you can communicate with the service from your activity using binding.
So basically comparing with the first suggested approach, you'll need some instance that will start and stop the service, but the communication between activities and service will be the same - using binding.
Yes, using a bound service in Android is a much better option when communicating with Views like Activities/Fragments. This is because of the following reasons,
It runs synchronously.
You can have more control on the service data when to show on UI thread of the view. You can choose when to call it in async/sync way.
LocalBroadcastManager only runs Asynchronously.

Communication between Activity, Service and Notification

I have 3 components the need to talk to each other:
Activity <---> Service <---> Notification
^ ^
| |
----------------------------------
The notification is started from the service and it needs to have custom view with buttons. Clicking on any of the button should send something to the activity and the service.
What is the best way of implementing this?
The options that I see:
Broadcast Receivers
Event bus
Eventbus is definitely not a consideration for interaction here. The Eventbus will only function within the same process in which it's created. That means it's maybe possible to communicate with your Service from your activity with Eventbus, but only if the service is a part of the Activity's process, which generally they shouldn't be (that's what threads are for). So I would strongly advise against that. And notifications are definitely not in the scope of the Eventbus.
You must use Android's documented infrastructure for the interactions you require.
From the Eventbus frontpage:
performs well with Activities, Fragments, and background threads
Broadcast receivers and intents are the best place to start with communications between the components you are using. Check out the answer to this question on how to use the Broadcast Receiver in your fragment to receive intents from a service.
You can also look into Service Binding if you need to have some tighter communication between your service and activity, but again, try to avoid that if you can because it can get very complicated very quickly.
For notifications, it really depends how complicated they are, but start with just building a Notification locally and you will start to understand what you can do with them. You'll notice that they also heavily make use of Intents.
Finally, read this article I wrote about (one) correct use of the EventBus.
Event bus best solution to interaction with components

onStartListener available for an activity

I have a series of activities, one of which is called UserActivity. What I'd like to do is have an object ListenerObject, that listens specifically for when UserActivity starts or stops. That is, I want UserActivity.onStart() to call ListenerObject.onActivityStart() (or some method named similarly).
I know that I can create an observer pattern set of classes to do this, but I'm wondering if there already exists such a framework within the Android API, and, more importantly, an accepted set of use patterns.
You could do this through Broadcasts:
http://developer.android.com/reference/android/content/BroadcastReceiver.html
http://developer.android.com/guide/components/intents-filters.html
In a few ways...
1) Have both activities receive and start from the same intent.
2) have activity 1 launch a broadcast to activity 2.
If ListenerObject makes sense as a static singleton you can just call the method on it during onStart() and onStop():
MySingleton.getSharedInstance().onActivityStart();
which would save you some overhead of the other valid methods mentioned.
The Android devs mention static singletons in the context of lazy creation for speed and reduced memory usage quite a bit it seems so it seems like an accepted pattern.
Depends on the required life cycle of the ListenerObject.
Seems like you want it to be around when the UserActivity isn't, but what about when you have none of your Activities on screen?
You could start a Service and then bind / unbind to it in your UserActivity's onStart / onStop. The service would likely stay alive whilst your app was in the background.
You could (un)bind to a service in all your Activities' onStart/Stop and provide an IBinder interface which asks would allow the service to ask the Activity if it is the UserAnctivity. The service would live whilst you navigate the app, but die once you put it in the background or go to another activity that doesn't bind to it (probably not what you want if you're doing something with G+ authentication / in app purchases etc).
You could (like others suggest) create a singleton, which won't die until the Application does, but won't keep it alive either.
You could have an Event Bus where the Listener subscribes to a known event published by the UserActivity.
shrug just some ideas

Using Intents or an event bus to communicate within the same app

I understand how to use Intents to communicate with the system/other apps. I understand how to use Intents within the same App. I also understand how to use Otto to communicate within the same App.
What are the Pro/Cons of using Otto vs. Intents to communicate between my Activities/Services?
Pros for using Otto:
You get to design your own event types, versus having to use custom actions or something to distinguish one Intent from another
Everything is within your own process (contrast with startActivity() and kin, which always involve IPC, even if the activity you are starting is in your own app), for speed and security
A bit less coding, as you aren't having to instantiate IntentFilter or BroadcastReceiver objects
It offers the producer pattern (as a quasi-replacement for sticky broadcasts)
Being not part of the OS, it has the potential to be updated more frequently
Cons for using Otto:
It cannot start an activity
It cannot start a service
It cannot bind to a service
It cannot send a broadcast
It cannot be used in a PendingIntent or for any true IPC
IOW, the true comparison for Otto is with LocalBroadcastManager, not with the general use of Intents.

How can I bind two Android Activities to one Service?

I would like to ask for some example, where two different activities (a button in the first activity opens a second activity), are communicating with one service (AIDL, etc.).
I've tried many different tutorials, but they are only about how to make one activity → one service.
This is probably old, but I'll try to answer it anyway...
In Android, seeing as only one Activity can bind to a Service at a time, and only one Activity can be shown at a time, there isn't any real reason to want to bind two Activities at a time.
But, if you'd like, the best solution is to bind the Service in the onResume() method, and unbind it in the onPause() method. This allows you to give two unrelated Activities access to the service, while only having one bound at a time.
Each Activity is responsible for binding and unbinding from the Service. This is normally done in onResume / onPause, or onStart / onStop, depending on your requirements. One Activity cannot bind another Activity to a Service. That's just the way it is. :)
You can do it by using Messenger that provide IPC communication without using AIDL. This is how you can bind multiple activities to a service.
If you need your service to communicate with remote processes, then
you can use a Messenger to provide the interface for your service.
This technique allows you to perform inter-process communication (IPC)
without the need to use AIDL.
Have a look at this link. When you see the code, you will find a switch case within a Handler. This will cater to the multiple requests that you will send from you multiple activities/components.

Categories

Resources