Skip to content

Commit 101c449

Browse files
committed
Avoid memory leak by only registering callback while attached to window.
Bug: 6710307 Change-Id: Idf57251e6feb48ec3e75e797144ff800fa874cc8
1 parent 2dde147 commit 101c449

File tree

1 file changed

+32
-2
lines changed

1 file changed

+32
-2
lines changed

core/java/android/app/MediaRouteButton.java

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ public class MediaRouteButton extends View {
3838
private final MediaRouteCallback mRouterCallback = new MediaRouteCallback();
3939
private int mRouteTypes;
4040

41+
private boolean mAttachedToWindow;
42+
4143
private Drawable mRemoteIndicator;
4244
private boolean mRemoteActive;
4345
private boolean mToggleMode;
@@ -131,13 +133,22 @@ public void setRouteTypes(int types) {
131133
// Already registered; nothing to do.
132134
return;
133135
}
134-
if (mRouteTypes != 0) {
136+
137+
if (mAttachedToWindow && mRouteTypes != 0) {
135138
mRouter.removeCallback(mRouterCallback);
136139
}
140+
137141
mRouteTypes = types;
142+
143+
if (mAttachedToWindow) {
144+
updateRouteInfo();
145+
mRouter.addCallback(types, mRouterCallback);
146+
}
147+
}
148+
149+
private void updateRouteInfo() {
138150
updateRemoteIndicator();
139151
updateRouteCount();
140-
mRouter.addCallback(types, mRouterCallback);
141152
}
142153

143154
public int getRouteTypes() {
@@ -207,6 +218,25 @@ public void setVisibility(int visibility) {
207218
}
208219
}
209220

221+
@Override
222+
public void onAttachedToWindow() {
223+
super.onAttachedToWindow();
224+
mAttachedToWindow = true;
225+
if (mRouteTypes != 0) {
226+
mRouter.addCallback(mRouteTypes, mRouterCallback);
227+
updateRouteInfo();
228+
}
229+
}
230+
231+
@Override
232+
public void onDetachedFromWindow() {
233+
if (mRouteTypes != 0) {
234+
mRouter.removeCallback(mRouterCallback);
235+
}
236+
mAttachedToWindow = false;
237+
super.onDetachedFromWindow();
238+
}
239+
210240
@Override
211241
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
212242
final int widthSize = MeasureSpec.getSize(widthMeasureSpec);

0 commit comments

Comments
 (0)