package com.atmob.keyboard_android.util;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;

import java.lang.reflect.InvocationTargetException;

/**
 * Context工具类
 */
public class ContextUtil {
    @SuppressLint("StaticFieldLeak")
    private static Context sContext;

    private ContextUtil() {
    }

    /**
     * 获取上下文Context
     */
    public static Context getContext() {
        if (sContext == null) {
            sContext = getApplicationByReflect();
        }
        return sContext;
    }

    /**
     * 反射ActivityThread获取Context
     */
    private static Application getApplicationByReflect() {
        try {
            @SuppressLint("PrivateApi")
            Class<?> activityThread = Class.forName("android.app.ActivityThread");
            Object thread = activityThread.getMethod("currentActivityThread").invoke(null);
            Object app = activityThread.getMethod("getApplication").invoke(thread);
            if (app == null) {
                throw new NullPointerException("u should init first");
            }
            return (Application) app;
        } catch (NoSuchMethodException | IllegalAccessException
                 | InvocationTargetException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        throw new NullPointerException("u should init first");
    }
}
