DEFINING AIDL OBJECTS
Let's say we want to define AIDL that we will use to communicate UI Fragment with AndroidService.
/** calls UI to Service **/
MyServiceAIDL.aidl
interface CommandServiceAIDL {
void setSomething(double value);
}
/** callbacks service to UI **/
MyListenerAIDL.aidl
interface MyListenerAIDL {
void onSomeEvent( boolean isOn);
}
ONCE YOU HAVE YOUR AIDL DEFINED
Let's say we have a UI Fragment
import android.content.ServiceConnection;
public class MyFragment extends Fragment implements ServiceConnection {
// ...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// we have to BIND this UI to AIDL service
getActivity().getApplicationContext().bindService(new Intent(CommandConst.ACTION_BIND_SERVICE), this, Context.BIND_AUTO_CREATE);
}
// ...
@Override
public void onDestroy() {
super.onDestroy();
// WE have to UNBIND this UI form AIDL service
getActivity().getApplicationContext().unbindService(this);
}
// class that has all my AIDL methods
private MyServiceAIDL myServiceAIDL;
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
myServiceAIDL = MyServiceAIDL.Stub.asInterface(service);
try {
// register this fragment as a client of the AIDL service
myServiceAIDL.register(TAG, myServiceAIDL Callback);
myServiceAIDL.setSomething(123.5);
}
catch (RemoteException e) {
Log.e(TAG, e.getMessage(), e);
}
}
private void doSomething(double value) {
try {
myServiceAIDL.setSomething(value);
}
catch (RemoteException e) {
e.printStackTrace();
}
}
// CALLBACKS
private final MyListenerAIDL.Stub commandServiceCallback = new SimpleCommandServiceListener() {
@Override
public void onSomeEvent(final boolean isOn) throws RemoteException {
handler.post(new Runnable() {
@Override
public void run() {
if (someSwitch.isChecked() != isOn) {
someSwitch.setChecked(isOn);
}
}
});
}
}
No comments:
Post a Comment