9527H
V2EX  ›  Android

android 项目,把一个子模块打成 jar 包,在 jar 包中如何获取 application??

  •  
  •   9527H · Oct 31, 2022 · 12217 views
    This topic created in 1295 days ago, the information mentioned may be changed or developed.

    android 项目,把一个子模块打成 jar 包,用 adb 命令执行 jar 包。但是代码中获取到 application 都是为空

    是因为 apply plugin: 'com.android.library'这个的缘故吗?

    获取代码如下 private static Application currentApplication;

    /**
     * 获取全局的 application
     *
     * @return 返回 application
     */
    @SuppressLint("PrivateApi")
    public static Application getNewApplication() {
        try {
            if (currentApplication == null) {
                currentApplication = (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null, (Object[]) null);
            }
            return currentApplication;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    3 replies    2022-11-01 10:33:14 +08:00
    ByteRan
        1
    ByteRan  
       Oct 31, 2022
    大哥,系统性过一下 Androi 的基本知识吧
    ikas
        2
    ikas  
       Oct 31, 2022
    获取 context 足够

    public static Context getLimitedSystemContext() {
    var currentActivityThread = ActivityThread.currentActivityThread();
    if (null == currentActivityThread) {
    synchronized (ActivityThread.class) {
    currentActivityThread = ActivityThread.currentActivityThread();
    if (null == currentActivityThread) {
    if (Looper.getMainLooper() == null) {
    Looper.prepareMainLooper();
    }
    currentActivityThread = ActivityThread.systemMain();
    }
    }
    }
    var limitedSystemContext = (Context) currentActivityThread.getSystemContext();
    return limitedSystemContext;
    }
    9527H
        3
    9527H  
    OP
       Nov 1, 2022
    @ikas 我没有执行 Activity 也可以吗?我是要在非 Activity 的类里使用 Application
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   963 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 21:52 · PVG 05:52 · LAX 14:52 · JFK 17:52
    ♥ Do have faith in what you're doing.