Android应用程序onCreate在Activity onCreate之前未被调用

4

在 Google Play 上,当我尝试访问静态 Application 实例时,我收到一个 NullPointerException。它出现在不同的 Android 操作系统版本上:Android 9、8 和 6。

从代码中看,Application.onCreate() 没有被调用,或者是在 Activity.onCreate() 之后调用。

我看过类似的问题,但没有任何有用的回复:

Application onCreate called(not called) after Activity onCreate

Android Activity::onCreate called before Application.onCreate

作为一个旁白的解决方案,我将创建一个基于 Context 的单例类,并使用 Context 获取它。但是,我不确定它如何与 Dagger 协作。

我的问题是:

  1. 这是 Android 的 bug 吗?
  2. 我做错了什么吗?
  3. 其他开发者是如何解决这个问题的?
public class App extends androidx.multidex.MultiDexApplication implements Application.ActivityLifecycleCallbacks, ComponentCallbacks2 {
    private static App instance;

    public static App getInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;

        // init singletone
    }

    private Singletone singletone;

    public Singletone getSingletone() {}
}

public class MainActivity extends androidx.appcompat.app.AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // On Google Play it produces NullPointerException

        Singletone singletone = App.getInstance().getSingletone();
    }
}

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.package.name">
    <application
        android:name=".app.App"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme.NoActionBar"
        android:largeHeap="true"
        >

        <activity
            android:name=".activities.MainActivity"
            android:screenOrientation="portrait"
            android:launchMode="singleTask"
            android:windowSoftInputMode="adjustPan"
            android:theme="@style/AppTheme.NoActionBar.Launcher"
            >
        </activity>
    </application>
</manifest>

你的MainActivity没有启动器意图过滤器或者你没有在这里编写它吗? - H.Taras
展示 "// init singletone" 代码。 - Onik
@H.Taras,MainActivity 包含启动器意图过滤器。你说得对,我只是没有在这里发布它。 - Oleksandr Sarapulov
@Onik,这里有类似于新的 Singleton(Context context) 的东西。在 Singleton 构造函数中,我只是从 context 中获取应用程序上下文。并从中初始化 Mixpanel 分析。就这样。 - Oleksandr Sarapulov
我有同样的问题。我意识到当活动启动时,应用程序尚未完全初始化。我的应用程序中有一个静态设置成员。它在onCreate()中填充。我非常确定它已经工作了很多年。也许这是AndroidX的问题... - The incredible Jan
1个回答

0

你需要将 instance = this; 从 onCreate() 方法移动到 App 的构造函数中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接