Reputation: 2570
I have Two activities here. Each of them will interact with a single Service i tried to Bind with.
But is it bad if I put in every onStart() method of each activities the binding code?
protected void onStart() {
super.onStart();
if(playIntent==null){
playIntent = new Intent(this, MusicService.class);
bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
startService(playIntent);
}
}
What about if from Activity - A i go to Activity - B, and then pressing the Back button? Would it be okay because Android will call onStart() method again, which means rebinding it again?
Rebinding twice from same Activity would it be bad practice or something?
The reference i got about the activity process is taken from here.
Upvotes: 0
Views: 774
Reputation: 1890
This is what i found on android developer site:
You should usually pair the binding and unbinding during matching
bring-up and
tear-down moments of the client's lifecycle.
For example:
If you only need to interact with the service while your activity is visible, you should bind during onStart() and unbind during onStop().
If you want your activity to receive responses even while it is stopped in the background, then you can bind during onCreate() and unbind during onDestroy().
Beware that this implies that your activity needs to use the service the entire time it's running (even in the background), so if the service is in another process, then you increase the weight of the process and it becomes more likely that the system will kill it.
Note: You should usually not bind and unbind during your activity's onResume() and onPause(), because these callbacks occur at every lifecycle transition and you should keep the processing that occurs at these transitions to a minimum. Also, if multiple activities in your application bind to the same service and there is a transition between two of those activities, the service may be destroyed and recreated as the current activity unbinds (during pause) before the next one binds (during resume).
Upvotes: 4