I want to create an interface which will interact with an already running Service from the Activity in foreground. viz, if there is a service called MyService running in background and I want to use the methods defined in the service from an activity called MyActivity then how will I do it.
-
There are lots of interface example out there for **Java** search it and you would get an idea. – Pankaj Oct 25 '15 at 10:25
3 Answers
There are several possibilities for an activity to communicate with a service and vice versa.
LocalBroadcast receiver that is provided by Android framework , v4 support library also provided.
AIDL for services in a different process
Handler and ResultReceiver or Messenger
To get details implementation visit following links : http://www.vogella.com/tutorials/AndroidServices/article.html
http://developer.android.com/guide/components/services.html

- 5,721
- 2
- 27
- 34
You need to make your service bindable. or more specifically something like this LocalService taken from the android guide.

- 8,354
- 13
- 55
- 103
The above answers are pretty apt ....but if you are bent on interfaces then... below is how one can do using interfaces ...but a better and more preferred way is described here
Create a Interface
with a function as below:
public interface OnChangeListener {
void onChange();
}
then in your service :
private OnChangeListener changeListener;
public void setChangeListener(OnChangeListener changeListener) {
this.changeListener = changeListener;
}
Some where in your service :
changeListener.onChange();
then from your Activity do this :
MyService.getInstance(this)
.setChangeListener(new OnChangeListener() {
@Override
public void onChange() {
// do something here
}
});

- 1
- 1

- 1,910
- 2
- 28
- 33
-
can we **getInstance** from every activity of the application – Yashodhan Singh Rathore Oct 25 '15 at 10:43
-
yes from every activity ..It is a static function to maintain only one instance, Though this is not right approach to use services. – Anudeep Samaiya Oct 25 '15 at 10:46
-
i already created a static method like **getInstance** in the service but it works only in the activity in which the service starts and returns null for every other activity. My static concepts are not very clear :p – Yashodhan Singh Rathore Oct 25 '15 at 10:51
-
can u tell me how to get the service instance from every activity of the app – Yashodhan Singh Rathore Oct 25 '15 at 10:53
-