Skip to content

Commit 3cd4624

Browse files
adampAndroid (Google) Code Review
authored andcommitted
Merge "Avoid memory leak by only registering callback while attached to window." into jb-dev
2 parents 0b9b053 + 101c449 commit 3cd4624

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
@@ -39,6 +39,8 @@ public class MediaRouteButton extends View {
3939
private final MediaRouteCallback mRouterCallback = new MediaRouteCallback();
4040
private int mRouteTypes;
4141

42+
private boolean mAttachedToWindow;
43+
4244
private Drawable mRemoteIndicator;
4345
private boolean mRemoteActive;
4446
private boolean mToggleMode;
@@ -132,13 +134,22 @@ public void setRouteTypes(int types) {
132134
// Already registered; nothing to do.
133135
return;
134136
}
135-
if (mRouteTypes != 0) {
137+
138+
if (mAttachedToWindow && mRouteTypes != 0) {
136139
mRouter.removeCallback(mRouterCallback);
137140
}
141+
138142
mRouteTypes = types;
143+
144+
if (mAttachedToWindow) {
145+
updateRouteInfo();
146+
mRouter.addCallback(types, mRouterCallback);
147+
}
148+
}
149+
150+
private void updateRouteInfo() {
139151
updateRemoteIndicator();
140152
updateRouteCount();
141-
mRouter.addCallback(types, mRouterCallback);
142153
}
143154

144155
public int getRouteTypes() {
@@ -213,6 +224,25 @@ public void setVisibility(int visibility) {
213224
}
214225
}
215226

227+
@Override
228+
public void onAttachedToWindow() {
229+
super.onAttachedToWindow();
230+
mAttachedToWindow = true;
231+
if (mRouteTypes != 0) {
232+
mRouter.addCallback(mRouteTypes, mRouterCallback);
233+
updateRouteInfo();
234+
}
235+
}
236+
237+
@Override
238+
public void onDetachedFromWindow() {
239+
if (mRouteTypes != 0) {
240+
mRouter.removeCallback(mRouterCallback);
241+
}
242+
mAttachedToWindow = false;
243+
super.onDetachedFromWindow();
244+
}
245+
216246
@Override
217247
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
218248
final int widthSize = MeasureSpec.getSize(widthMeasureSpec);

0 commit comments

Comments
 (0)