Android Binder漏洞

yyd*_*ydl 0 service android

我刚刚阅读http://www.ozdroid.com/#!BLOG/2010/12/19/How_to_make_a_local_Service_and_bind_to_it_in_Android,了解绑定到本地服务时内存泄漏的方式......

我目前正在使用以下代码实现对本地服务的绑定.

在我的服务中:

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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

定义IStreamCommander的地方:

public interface IStreamCommander {
 void registerPlayer(IStreamListener callback);
 void removePlayer(IStreamListener callback);
 void play(Station SongID);
 void stop();
}
Run Code Online (Sandbox Code Playgroud)

和IStreamListener定义:

public interface IStreamListener {
 void updateUI(String msg, int buttons);
}
Run Code Online (Sandbox Code Playgroud)

然后我在活动中有这个:

this.bindService(startedSvc, svcConn, 0);
Run Code Online (Sandbox Code Playgroud)

private ServiceConnection svcConn = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder binder) {
        service = (IStreamCommander) binder;
    }

    public void onServiceDisconnected(ComponentName className) {
        service = null;
    }
};
Run Code Online (Sandbox Code Playgroud)

我是在泄漏记忆,还是这样可以吗?

Com*_*are 6

如果你要坚持使用绑定模式,我会:

  • 移动Binder到独立的公共类,而不是内部类
  • 绑定使用getApplicationContext(),而不是this
  • 确保onRetainNonConfigurationInstance()在配置更改(例如,屏幕旋转)时正确使用您的活动实例之间的绑定

这是一个示例项目.