Reputation: 24464
I just read http://www.ozdroid.com/#!BLOG/2010/12/19/How_to_make_a_local_Service_and_bind_to_it_in_Android about how there can be memory leaks when binding to a local service...
I am currently implementing binding to a local service using the following code.
In the service I have:
private final Binder binder=new LocalBinder();
public class LocalBinder extends Binder implements IStreamCommander {
public void registerPlayer(IStreamListener callback) {
theUI=callback;
}
public void removePlayer(IStreamListener callback) {
theUI=null;
}
public void play(Station NowP) {
playURL(NowP);
}
public void stop() {
stopIt();
}
}
Where IStreamCommander is defined:
public interface IStreamCommander {
void registerPlayer(IStreamListener callback);
void removePlayer(IStreamListener callback);
void play(Station SongID);
void stop();
}
and IStreamListener is defined:
public interface IStreamListener {
void updateUI(String msg, int buttons);
}
I then have this in the activity:
this.bindService(startedSvc, svcConn, 0);
and
private ServiceConnection svcConn = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
service = (IStreamCommander) binder;
}
public void onServiceDisconnected(ComponentName className) {
service = null;
}
};
So am I leaking memory, or is this okay?
Upvotes: 0
Views: 4878
Reputation: 1006594
If you are going to stick with the binding pattern, I would:
Binder
to a standalone public class, not an inner classgetApplicationContext()
, rather than this
onRetainNonConfigurationInstance()
properly to pass your binding between instances of your activity when the configuration changes (e.g., screen rotation)Here is a sample project demonstrating this.
Upvotes: 9