In the client activity or fragment, bind to the service and use the AIDL interface to invoke methods.
public class MainActivity extends AppCompatActivity {
private ICurrencyConverter mService;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// Obtain the AIDL interface proxy
mService = ICurrencyConverter.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
};
@Override
protected void onStart() {
super.onStart();
// Bind to the CurrencyConverterService
Intent intent = new Intent(this, CurrencyConverterService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
// Unbind from the service
unbindService(mConnection);
}
public void onConvertButtonClicked(View view) {
try {
String fromCurrency = "USD";
String toCurrency = "EUR";
float amount = 100;
float convertedAmount = mService.convertCurrency(fromCurrency, toCurrency, amount);
Toast.makeText(this, "Converted Amount: " + convertedAmount, Toast.LENGTH_SHORT).show();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}