Get actual app ID and version from Android library without Context

References:

This addresses the scenario where you are writing an Android library/SDK and it’s used in an app. How to get the actual app ID (package name) and version from inside the SDK? BuildConfig.APPLICATION_ID and BuildConfig.VERSION_NAME would return the package name and version for your SDK, not for the app that your SDK is currently running in. The POJO class below (which you would put in your SDK) shows how to do it, without the need to retrieve Context.

package sg.zion.mysdk;

import android.app.Application;
import android.content.pm.PackageInfo;
import android.webkit.WebSettings;

import sg.zion.mysdk.BuildConfig;

import java.lang.reflect.Method;

public class Utils {
    protected static String userAgent = null;

    public static String getUserAgent() {
        if (null == userAgent) { // do this once and store it
            Class clazz;
            Method method;
            String appPackageName = "";
            String appVersion = "";
            String appDetails = "";

            try {
                clazz = Class.forName("android.app.ActivityThread");
            } catch (Exception e) {
                clazz = null;
            }

            if (clazz != null) {
                try {
                    method = clazz.getDeclaredMethod("currentPackageName");
                    appPackageName = (String) method.invoke(clazz);
                } catch (Exception e) {
                    appPackageName = "";
                }

                try {
                    method = clazz.getDeclaredMethod("currentApplication");
                    Application app = (Application) method.invoke(clazz);
                    PackageInfo pinfo = app.getPackageManager().getPackageInfo(
                            appPackageName, 
                            0
                    );
                    appVersion = pinfo.versionName;
                } catch (Exception e) {
                    appVersion = "";
                }
            }

            appDetails = appPackageName 
                    + (appVersion.isEmpty() ? "" : "/" + appVersion);

            userAgent = WebSettings.getDefaultUserAgent(null)
                    + " " + BuildConfig.APPLICATION_ID
                    + "/" + BuildConfig.VERSION_NAME
                    + (appDetails.isEmpty() ? "" : " " + appDetails);
        }

        return userAgent;
    }
}