0

Normal way of using a bound service:

private ServiceConnection musicConnection = new ServiceConnection() {

  public void onServiceConnected(ComponentName name, IBinder service) { 
    MusicBinder binder = (MusicBinder)service;
    //get service
    musicSrv = binder.getService();
    //pass list

    musicBound = true;
  }

  @Override
  public void onServiceDisconnected(ComponentName name) {
    musicBound = false;
  }
};



Intent  playIntent = new Intent(this, MusicService.class);
bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE); 

Instead of this, can't we use this:

MusicService music=new MusicService();

If yes, will there be any differences between the two instances obtained in two different ways?

Mukesh Ram
  • 6,248
  • 4
  • 19
  • 37
Kishan Kumar
  • 685
  • 1
  • 5
  • 17
  • `new MusicService();` doesn't bind to anything, it just constructs an object – OneCricketeer Aug 10 '16 at 04:49
  • I agree. But as per me the main reason behind binding is to get an instance of service object .That's why we have to implement the onBind method in the service class .This method returns a binder which ultimately returns the service object itself . – Kishan Kumar Aug 10 '16 at 05:20
  • Same as `Activity`, you cannot new a Activity. – Weiyi Aug 10 '16 at 06:00

1 Answers1

2

Bind service or start service will result in a corresponding call to the target service's life cycle methods. If this service is not already running, it will be instantiated and started (creating a process for it if needed); if it is running then it remains running.

New a service is just create a new object, means nothing, system knows nothing about it.

Just like activity, you cannot new a activity, you should start a activity, then ActivityManager will be response for create the Activity instance and calls its onCreate method.

Weiyi
  • 1,843
  • 2
  • 22
  • 34