Skip to content

Commit

Permalink
fix handler memory leak
Browse files Browse the repository at this point in the history
  • Loading branch information
lightSky committed Aug 11, 2015
1 parent 91d3ca3 commit 0aeb786
Showing 1 changed file with 32 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import android.view.animation.Interpolator;
import android.widget.RelativeLayout;

import java.lang.ref.WeakReference;
import java.lang.reflect.Field;

import cn.lightsky.infiniteindicator.indicator.PageIndicator;
Expand All @@ -26,6 +27,7 @@
* Thanks to: https://github.com/Trinea/android-auto-scroll-view-pager
*/
public class InfiniteIndicatorLayout extends RelativeLayout implements RecyclingPagerAdapter.DataChangeListener {
private final ScrollHandler handler;
private PageIndicator mIndicator;
private ViewPager mViewPager;
private Context mContext;
Expand Down Expand Up @@ -113,6 +115,7 @@ else if(indicatorType == 1)
else
LayoutInflater.from(context).inflate(R.layout.layout_anim_line_indicator, this, true);

handler = new ScrollHandler(this);
mViewPager = (ViewPager) findViewById(R.id.view_pager);
mRecyleAdapter = new RecyleAdapter(mContext);
mRecyleAdapter.setDataChangeListener(this);
Expand Down Expand Up @@ -180,6 +183,11 @@ private void sendScrollMessage(long delayTimeInMills) {
handler.sendEmptyMessageDelayed(MSG_WHAT, delayTimeInMills);
}

private void sendScrollMessage() {
/** remove messages before, keeps one message is running at most **/
sendScrollMessage(interval);
}

/**
* modify duration of ViewPager
*/
Expand Down Expand Up @@ -270,19 +278,30 @@ public void notifyDataChange() {
mIndicator.notifyDataSetChanged();
}

private Handler handler = new Handler(){
public static class ScrollHandler extends Handler{
public WeakReference<InfiniteIndicatorLayout> mLeakActivityRef;

public ScrollHandler(InfiniteIndicatorLayout infiniteIndicatorLayout) {
mLeakActivityRef = new WeakReference<InfiniteIndicatorLayout>(infiniteIndicatorLayout);
}

@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case MSG_WHAT:
scrollOnce();
sendScrollMessage(interval);
default:
break;

InfiniteIndicatorLayout infiniteIndicatorLayout = mLeakActivityRef.get();
if(infiniteIndicatorLayout != null){
switch (msg.what) {
case MSG_WHAT:
infiniteIndicatorLayout.scrollOnce();
infiniteIndicatorLayout.sendScrollMessage();
default:
break;
}
}
}
};
}


/**
* get auto scroll interval time in milliseconds, default is {@link #DEFAULT_INTERVAL}
Expand Down Expand Up @@ -428,4 +447,9 @@ public void setOnPageChangeListener(ViewPager.OnPageChangeListener onPageChangeL
mIndicator.setOnPageChangeListener(onPageChangeListener);
}

@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
handler.removeCallbacksAndMessages(null);
}
}

0 comments on commit 0aeb786

Please sign in to comment.