0

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 Answers3

1

There are several possibilities for an activity to communicate with a service and vice versa.

  1. LocalBroadcast receiver that is provided by Android framework , v4 support library also provided.

  2. AIDL for services in a different process

  3. 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

USKMobility
  • 5,721
  • 2
  • 27
  • 34
0

You need to make your service bindable. or more specifically something like this LocalService taken from the android guide.

Ofek Ron
  • 8,354
  • 13
  • 55
  • 103
0

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
                        }
                    });
Community
  • 1
  • 1
Anudeep Samaiya
  • 1,910
  • 2
  • 28
  • 33