Get the object of a running service

EyeQ Tech picture EyeQ Tech · Jul 11, 2014 · Viewed 7.9k times · Source

Background: I'm running a background service (independent of the app opened or not) to maintain connection with Tizen-based app on Gear2 (not Android, hence the manual maintenance).

Whenever my phone apps (multiple apps) have data to send to send to the service, I need to get the 'connection' object inside the service and call 'send'.

So my question is: how can I get running service object?

If I can get that service, my code will be like this:

MyConnection  connection = runningService.getConnection()
connect.send(message); 

Thanks.

Answer

Gilad Haimov picture Gilad Haimov · Jul 11, 2014

If it's only a single object (say connection) you need to periodically access, I would probably make it to be a singleton, which is created by the services and available to the other components of your app:

class MyConnection {
   private static MyConnection inst;

   public static void set(........) { <-------- set by service
   }


  public static getInstance() { return inst; } <------- and accessible to other components 
}


But, if you need a more elaborate and continuous interaction with your service, you should probably set it to be a bound service, and hand craft the interface you would like it to implement:


Create a Bound Service:

class MyConnectionService extends Service {

    private final IBinder myBinder = new MyLocalBinder();

    @Override
    public IBinder onBind(Intent arg0) {
        return myBinder;
    }

    public ConnectionRecord getConnection() {
        return myConnection;
    }

    public class MyLocalBinder extends Binder {
            MyConnectionService getService() {
               return MyConnectionService.this;
            }
        }
    }


And bind to it from another component, e.g. an Activity:

public class MyActivity extends Activity {

    MyConnectionService serviceConnector;
    boolean isBound = false;

    private ServiceConnection serviceConnector = new ServiceConnection() {

        public void onServiceConnected(ComponentName className,
                IBinder service) {
            MyLocalBinder binder = (MyLocalBinder) service;
            serviceConnector = binder.getService(); //<--------- from here on can access service!
            isBound = true;
        }

        public void onServiceDisconnected(ComponentName arg0) {
            serviceConnector = null;
            isBound = false;
        }

       };
.
.
.
}


Note that after onServiceConnected() is completed you will have a serviceConnector object you can use to communicate with the service, which is what we aimed for.