android 线程管理类

1. 延时任务以及取消延时的应用场景:实时搜索,文字内容变化时候不发送请求,当停止变化指定时间后再发送请求

2. 使用方法:

// 回到主线程
MainThreadHelper.runOnUIthread(new Runnable() {
                    @Override
                    public void run() {
                       // pushActivity();
                    }
});
// 延时调用以及取消延迟
MainThreadHelper.runDelayedCall(300, new MainThreadHelper.DelayedCallListener() {
            @Override
            public void onClick() {
              //  animalHiddenView();
            }
});

3. 实现类代码:


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

/**
 * Created by jing on 17/5/19.
 * 线程管理~
 */
public class MainThreadHelper{
    private MainThreadHelper(){ super(); }
    // 单利模式
    private static MainThreadHelper mainThreadHelper = new MainThreadHelper();
    /**
     * 回到在主线程
     **/
    private MainThreadComplate mainThreadComplate = new MainThreadComplate();
    public static void runOnUIthread(Runnable runnable){
        mainThreadHelper.mainThreadComplate.runOnUIthread(runnable);
    }

    /**
    * 打印当前线程
    * */
    public static void logCurrentThread(){
        String string = Thread.currentThread().toString();
        Log.d("当前线程",string);
    }

    /** 延时任务以及取消延时 */
    private DelayedCallComplate delayedCallComplate = new DelayedCallComplate();
    public interface DelayedCallListener{
        void onClick();
    }
    public static void runDelayedCall(long delayMillis,DelayedCallListener listener){
        mainThreadHelper.delayedCallComplate.runDelayedCall(delayMillis,listener);
    }
}
/** 主线程相关类 */
class MainThreadComplate{
    private Handler handler = new Handler(Looper.getMainLooper());
    /** 回到在主线程 */
    public void runOnUIthread(Runnable runnable){
        if (Looper.myLooper() == Looper.getMainLooper()){
            runnable.run();
            return;
        }
        handler.post(runnable);
    }
}

/** 延时任务以及取消延时类 */
class  DelayedCallComplate implements Runnable{
    private MainThreadHelper.DelayedCallListener listener = null;
    private Handler handler = new Handler(Looper.getMainLooper());
    public void runDelayedCall(long delayMillis,MainThreadHelper.DelayedCallListener listener){
        this.listener = listener;
        handler.removeCallbacks(this);
        handler.postDelayed(this,delayMillis);
    }
    @Override
    public void run() {
        if (listener == null) return;
        listener.onClick();
    }
}

你可能感兴趣的:(android 线程管理类)