Android OS 6.0归零静态变量

时间:2017-06-01 18:06:54

标签: android android-6.0-marshmallow low-memory

我在Google Play中有很多痕迹,似乎应用程序类的静态成员为空。

我找到的所有相关帖子都是关于存储数据,但这些变量不是数据,它们是第三方SDK实例或其他使用单例模式和应用程序的关键对象。

Activity类中使用的数据存储在数据库中,并且没有使用静态引用。

这些痕迹不会报告给Fabric,这很奇怪,因为它是用Application onCreate方法初始化的。

跟踪表明当触发FirebaseMessagingService onMessageReceived方法时静态变量为空,我需要将消息传递给第三方SDK,但由于该实例为null,应用程序崩溃。 / p>

仅适用于Android OS 6.0的痕迹

有没有解决方案如何处理这个操作系统版本是如此积极的归零静态成员?

感谢。

以下是我使用的示例最小代码:

申请类:

@Override
public void onCreate() {
    Engine.init();
}

引擎类:

private static Engine sInstance;

private 3rdParty m3rdParty;

private Engine() {
    m3rdParty = new 3rdParty();
}

public static void init() {
    if (sInstance == null) {
        sInstance = new Engine();
    }
}

public static onMessageReceived(RemoteMessage remoteMessage) {
    sInstance.m3rdParty.onMessageReceived(remoteMessage);
    // Above line crashes with NPE, sEngine or m3rdParty is never set to null in code
}

扩展FirebaseMessagingService:

public void onMessageReceived(RemoteMessage remoteMessage) {
    Engine.onMessageReceived(remoteMessage);
}

1 个答案:

答案 0 :(得分:3)

  

有没有解决方案如何处理这个操作系统版本是如此积极的归零静态成员?

“OS”不是“归零静态成员”。最有可能的是,您的流程终止,无论是由于内存条件不佳还是用户操作(例如,在概览屏幕上滑动您的任务)。这是完全正常的。

我说“最有可能”,因为你的问题不包含minimal, complete, and verifiable example,包含堆栈跟踪和相关的源代码,所以我不能排除其他可能性。例如,如果您的代码在某些条件下将null分配给那些static字段,那么在您不期望的情况下可能会满足这些条件。