Android: using AIDL

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);
               }
            }
         });
      }
}


As an Amazon Associate I earn from qualifying purchases.

My favorite quotations..


“A man should be able to change a diaper, plan an invasion, butcher a hog, conn a ship, design a building, write a sonnet, balance accounts, build a wall, set a bone, comfort the dying, take orders, give orders, cooperate, act alone, solve equations, analyze a new problem, pitch manure, program a computer, cook a tasty meal, fight efficiently, die gallantly. Specialization is for insects.”  by Robert A. Heinlein

"We are but habits and memories we chose to carry along." ~ Uki D. Lucas


Popular Recent Articles