How to call Android Service methods from Activity?
This is a re-post of an answer I wrote on Stackoverflow
Forget everything you know and answer this question.
How do you call a normal Java class 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 which is created, destroyed and managed by Android OS.
For creating a service object we need IBinder.
This is the flow of getting a service object from IBinder.
Once you have a hold of serviceObject. It will work like any normal Java object.
The thing explained above in the figure is called Binding a Service.
Binding makes it possible to observe a background service from an Activity. With binding, we can communicate in both ways
ie Activity< β β>Service.
Few things to keep in mind
- Never forget to unbind the service else you will lead to ResourceLeak.
- You can call
startService(intent)
andbindService(mIntent, mConnection, BIND_AUTO_CREATE)
in any order. Binding and Starting a service are two independent things.
Putting up content takes a lot of time and effort π.
π clap π If you think you learned something from this article.You can find me on Stackoverflow,Github,and,on Linkedin.
Give feedback and feel free to correct mistakes.