Reputation: 103
I have an Android service which collects data from some external hardware. I am making that data available to my Activities using a callback structure shown here.
The data I'm making available is an ArrayList<MyClass>
. While reading the Android API docs, it seems that a suggested way is to use broadcast events and Parcelable
. I've also seen callbacks used in Android apps, so the question is what's the advantage of refactoring my code to use broadcasts?
Now, in the future, I am looking to allow external apps to access this service (Tasker, for example), so I'm guessing that the callback method I use will be for use in the local app only. So the question is how to do a callback from a Service
to an Activity
using an AIDL description.
Upvotes: 1
Views: 119
Reputation: 633
The way to allow a service to callback into an Activity is to have the service aidl interface define a registration function that takes another aidl interface as a parameter.
ServiceAidlInterface.aidl:
package com.test;
import com.test.CallbackAidlInterface;
interface ServiceAidlInterface {
void registerCallback(in CallbackAidlInterface callback);
}
CallbackAidlInterface.aidl:
package com.test;
interface CallbackAidlInterface {
void doCallback();
}
In your activity you need to define the following:
ServiceAidlInterface mService = null;
private CallbackAidlInterface mCallback = new CallbackAidlInterface.Stub() {
@Override
public void doCallback() throws RemoteException {
}
};
So when the activity binds your onServiceConnected() gets called you can do the following:
mService = ServiceAidlInterface.Stub.asInterface(serviceBinder);
service.registerCallback(mCallback)
Upvotes: 1