1

I know Bound Services Lives only until the Activity or any component needs it. We have to call the MyLocalBinder class from onBind function. Why is it so? Why can't we call it directly?

public class MyService extends Service {

private final IBinder myBinder = new MyLocalBinder();

public MyService() {
}

@Override
public IBinder onBind(Intent intent) {

    return myBinder;
}

public String getCurrentTime(){

    SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss", Locale.UK);
    return (df.format(new Date()));
}

public class MyLocalBinder extends Binder{

    MyService getService(){
        return MyService.this;
    }
}
}
Onik
  • 19,396
  • 14
  • 68
  • 91

1 Answers1

1

If you are using binder calls within the same application then it is a way of accessing some of your service class functionality from other components like activity.

If you are using binder api calls between applications this means your trying to use remote functionality from your application. Since two applications run in their own processes binder will acts like a pipe with security.

You can not call MyBinder class directly as you can not access service class members directly. Since bindservice provides a callback with binder object it is recommended to follow this approach.

siva
  • 1,850
  • 13
  • 14
  • But why do we use MyLocalBinder class to use the functionality? Why can't we access the service Directly? – Saurabh Saxena Sep 26 '15 at 04:27
  • We can always make an object of the service, use it in the main activity, but the fact that a bound service is to be called is it necessary to call MyLocalBinder class? – Saurabh Saxena Sep 26 '15 at 04:32
  • 1
    Service is an android application component. You should not create objects of Service, Activity, receiver etc... Android UI framework will do that after you make calls to bindservice, start activity. If you are creating these class objects manually this is like introducing memory leaks in the code. Also the framework will loose the control of these component's life cycle. – siva Sep 26 '15 at 04:38