android 防抖处理


import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;

import java.util.HashMap;

/**
 * 防抖处理工具类
 *  需求:
 *   1, N ms内只处理最后一次, 用于监听驱动,框架事件. 特点响应为最后正确的状态
 *   2, N ms内只处理第一次, 用Button 避免双击等场景. 特点及时响应,取消拖尾事件
 */

public class AntiShake {

    private static final String TAG = "AntiShake";
    //TODO the map will increase, how to release the unused key value pairs?
    private HashMap<Object, Long> mKeyMaps = new HashMap<Object, Long>();

    /**
     * delay to run
     */
   public void debounce(Handler handler , Runnable r, long delay) {
        if (handler.hasCallbacks(r)) {
            handler.removeCallbacks(r);
        }
        handler.postDelayed(r, delay);
    }

    /**
     * run right now
     */
    public void throttle(Runnable r, long delay) {
        Integer key = r.hashCode();
        Long lastTime = mKeyMaps.get(key);
        long now = SystemClock.uptimeMillis();
        // if first run or last run time is delay ms ago, run right now
        if (lastTime == null || lastTime + delay < now) {
            mKeyMaps.put(key, now);
            r.run();
        }
    }

}
应用:
private AntiShake mAntiShakeUtils = new AntiShake();
mAntiShakeUtils.debounce(mHandler, mRefreshAudioRouteUIRunnable, 500);

Handler:
private Handler mHandler = new MainHandler(this);
private static class MainHandler extends Handler{
WeakReference<AudioSettingsFragment> mAct;
MainHandler(AudioSettingsFragment activity){
mAct = new WeakReference<AudioSettingsFragment>(activity);
}

@Override
public void handleMessage(Message msg) {
AudioSettingsFragment context = mAct.get();
if(context==null) return;
mAct.get().handleMsg(msg);
}
}

private final Runnable mRefreshAudioRouteUIRunnable = new Runnable() {
@Override
public void run() {
initAudioPriority();
}
};

销毁:
mHandler.removeCallbacksAndMessages(null);
mHandler = null;

0