V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
9527H
V2EX  ›  Android

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

  •  
  •   9527H · 2022-10-31 21:25:25 +08:00 · 3374 次点击
    这是一个创建于 514 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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 条回复    2022-11-01 10:33:14 +08:00
    tanranran
        1
    tanranran  
       2022-10-31 21:51:27 +08:00
    大哥,系统性过一下 Androi 的基本知识吧
    ikas
        2
    ikas  
       2022-10-31 21:51:43 +08:00
    获取 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
       2022-11-01 10:33:14 +08:00
    @ikas 我没有执行 Activity 也可以吗?我是要在非 Activity 的类里使用 Application
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5942 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 02:35 · PVG 10:35 · LAX 19:35 · JFK 22:35
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.