开发者

Android Binder Leaks

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 voi开发者_如何转开发d 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?


If you are going to stick with the binding pattern, I would:

  • Move your Binder to a standalone public class, not an inner class
  • Bind using getApplicationContext(), rather than this
  • Make sure you use 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜