android中handler 轮询数据变化 使用WeakReference防止内存泄露

自己项目有个传感器传数据,需要一直监听,刷新页面操作,一直刷新页面才出现内存泄露

泄露的原因
Java 的强引用、弱引用、软引用、虚引用

考进项目里面直接用
方法

    private Runnable timerRun = new Runnable() {
        @Override
        public void run() {
            mOperationHandler.sendEmptyMessage(1);
        }
    };

 private OperationHandler mOperationHandler = new OperationHandler(new WeakReference
            <>(this));
  /**
     * 执行定时任务固定数量线程池
     */
    private ScheduledExecutorService timerThreads = Executors.newScheduledThreadPool(1);
 timerThreads.scheduleAtFixedRate(timerRun, 1500, 100, TimeUnit.MILLISECONDS);
 private static class OperationHandler extends Handler {

        WeakReference mWeakReference;

        OperationHandler(WeakReference weakReference) {
            this.mWeakReference = weakReference;
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            OperationActivity activity = mWeakReference.get();
            if (activity != null) {
                if (msg.what == 1) {
                    activity._handleWeightChanged();
                    自己做页面的操作
                }
            }
        }
    }
   @Override
    protected void onDestroy() {
        super.onDestroy();
        timerThreads.shutdownNow();
        mOperationHandler.removeCallbacksAndMessages(null);
    }

你可能感兴趣的:(android,源码)