首页 > 解决方案 > 应用程序进入后台后,Android 不会保持静态字段处于活动状态

问题描述

我正在构建一个安卓应用程序。
我创建了一个“BaseActivity”类,它与我的用户一起保存一个静态字段,所有其他活动都扩展了“BaseActivity”。

Application onCreate()我做期间:

BaseActivity.initializeUser();

它基本上为应用程序实例化了用户,这样之后我的所有活动都可以访问用户。

我绝对保证,代码中的任何地方用户都设置为 NULL

问题是:有时,当人们正常使用应用程序(生产)时,有时他们会在一段时间后得到nullpointerexception,因为活动试图访问用户中的某些字段并且它为空

根据 crashlytics,这总是在某些活动中发生oncreate(没有具体的,可以是任何)

为什么???

android 是否会丢弃我的单例对象以节省内存?如果是这样,为什么许多其他库(如 Firebase、Admob 和其他库)都有类似的初始化方法,在 Application onCreate() 期间调用但之后无论如何它们都可以在应用程序中正常运行?

====== 更新 =========

initializeUser就像:

 private static void initializeUser(){
        
        currentUser = new User();
        //then i do update the user's fields
        currentUser.setLocation(something); 
        currentUser.setRef(something);
        currentUser.setVersion(something);
        //these values are read from various places but all methods are SYNCHRONOUS and run on main thread
        
    }

currentUser is `private` and `static` and this method is the UNIQUE line of code that does an attribution to this field.

然而,用户在从该实体调用某些方法时得到 nullpointerexception...

标签: androidandroid-activityactivity-lifecycle

解决方案


推荐阅读