How to call methods of a Service from activity?

前端 未结 6 1334
不知归路
不知归路 2020-11-29 07:22

I simply want to call methods of a local service from my activity. How can i do that ?

6条回答
  •  不知归路
    2020-11-29 07:59

    How do you call a normal Java method?

    A obj = new A();
    obj.method();
    

    Service is a Java class. So how would you call a service method?

    serviceObj.method();
    

    Now the real question is how do you create a Service object?

    Service serviceObj = new Service();

    Definitely not.

    In Android, Service is a System component that is created, destroyed and managed by Android OS.
    For creating a service object you need IBinder.

    This is how you can get a Service object from IBinder.

    Once you have a hold of serviceObject. It will work like any normal Java object.
    The above thing explained in the figure is called Binding a Service.

    Binding makes possible to observe a background service from an Activity. With binding, we can communicate in both ways ie Activity<--->Service.
    Prateek Yadav has already provided an excellent code snippet. You can use that.

    Few things to keep in mind

    • Never forget to unbind the service else you will lead to ResourceLeak.
    • You can call startService(intent) and bindService(mIntent, mConnection, BIND_AUTO_CREATE) in any order. Binding and Starting a service are two independent things.

提交回复
热议问题