-1

Can someone show me example how to bind service to activity. For example, service is working in background and depending on how it worked it sends messages to activity and activity listens this messages. I can handle only simple service

 public class TimeService extends Service {
    //
        @Override
        public void onCreate() {
            super.onCreate();

        }

        @Override
        public int onStartCommand(Intent intent, int flags, int start_id) {

            return START_NOT_STICKY;
        }

        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    }
Jenya Kirmiza
  • 701
  • 2
  • 10
  • 27

1 Answers1

1

Bound services can get really complex take your pick of the methods.

http://developer.android.com/guide/components/bound-services.html

Extending ibinder only works for services in the same process. So if you goal is to build a super memory efficient service that runs in its own process you can't use this.

Using a messenger http://developer.android.com/guide/components/bound-services.html#Messenger Eclipse ADT LINT will show warning that the handler should be static. I made it static by using a weakReference to the context which I setup in onCreate for making application calls.

private static WeakReference<Context> weakContext = null;

public void onCreate() {
    ServiceLocationRecorder.weakContext = new WeakReference<Context>(
            getApplicationContext());
}

Get the context with the following code.

Context context = weakContext.get();
    if (context != null) {

AIDL http://developer.android.com/guide/components/aidl.html I tried AIDL and builds take a lot longer so If you have a slow machine like mine you'll be disappointed with the build times but it does work.

danny117
  • 5,581
  • 1
  • 26
  • 35