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

2022-10-31 21:25:25 +08:00
 9527H

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;
}
3989 次点击
所在节点    Android
3 条回复
tanranran
2022-10-31 21:51:27 +08:00
大哥,系统性过一下 Androi 的基本知识吧
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
2022-11-01 10:33:14 +08:00
@ikas 我没有执行 Activity 也可以吗?我是要在非 Activity 的类里使用 Application

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/891586

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX