1. 程式人生 > >Android中的弱引用(WeakReference)

Android中的弱引用(WeakReference)

 

  • 弱引用,其實弱字說明了一切——容易被銷燬(GC);舉個例子在Handler裡面如果直接引用了一個物件(強引用),handler在處理一個延時任務,期間主執行緒被使用者finish掉,但這裡的物件卻不能被銷燬,這樣造成記憶體洩漏,也容易造成NullPointException異常。
  • 每次GC做回收都會銷燬弱引用。
  • 常用與子執行緒或者handler裡面。
  • private static class BannerHandler extends Handler {
        private WeakReference<BannerView3> weakReference = null;
    
        public BannerHandler(BannerView3 bannerView) {
            super(Looper.getMainLooper());
            this.weakReference = new WeakReference<BannerView3>(bannerView);
        }
    
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (this.weakReference == null) {
                return;
            }
            BannerView3 bannerView = this.weakReference.get();
            if (bannerView == null || bannerView.mViewPager == null || bannerView.mViewPager.getAdapter() == null || bannerView.mViewPager.getAdapter().getCount() <= 0) {
                sendEmptyMessageDelayed(MSG_LOOP, LOOP_INTERVAL);
                return;
            }
        }
    }