android——如何优雅的将刷新工作交给主线程

在很多异步操作中,等结果返回后,需要刷新UI。而我们知道UI刷新必须是在主线程中完成。虽然方法很多,但我这里只讲其中一种。

在BaseApplication中记录主线程id

package com.songheng.eastfirst;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;

import com.songheng.eastfirst.business.applog.manager.AppLogManager;
import com.songheng.eastfirst.service.StatisticalService;
import com.songheng.eastfirst.utils.UIUtils;

public class BaseApplication {
    private static Context mContext;// Context对象
    private static Handler mHandler;// Handler对象
    private static Thread mMainThread;// Thread对象
    private static int mMainThreadId;// 主线程Id

       public static Application getApplication() {
        return application;
    }

    public static void setApplication(Application app) {
        application = app;
    }

    static Application application;
    public static Context getContext() {
        return mContext;
    }

    public static void setContext(Context context) {
        mContext = context;
    }

    public static Handler getHandler() {
        return mHandler;
    }

    public static void setHandler(Handler mHandler) {
        BaseApplication.mHandler = mHandler;
    }

    public static Thread getMainThread() {
        return mMainThread;
    }

    public static void setMainThread(Thread mMainThread) {
        BaseApplication.mMainThread = mMainThread;
    }

    public static int getMainThreadId() {
        return mMainThreadId;
    }

    public static void setMainThreadId(int mMainThreadId) {
        BaseApplication.mMainThreadId = mMainThreadId;
    }
  
   
}

Uitils工具类

public class UIUtils {

    public static int getMainThreadId() {
        return BaseApplication.getMainThreadId();
    }
    


    public static Handler getHandler() {
        return BaseApplication.getHandler();
    }
    
   // 判断是否是主线的方法
    public static boolean isRunInMainThread() {
        return getMainThreadId() == android.os.Process.myTid();
    }
    
        // 保证当前的UI操作在主线程里面运行
    public static void runInMainThread(Runnable runnable) {
        if (isRunInMainThread()) {
            // 如果现在就是在珠现场中,就直接运行run方法
            runnable.run();
        } else {
            // 否则将其传到主线程中运行
            getHandler().post(runnable);
        }
    }

}

 

posted @ 2018-01-30 16:33  shoneworn  阅读(1319)  评论(0编辑  收藏  举报