如何在应用程序启动时显示自定义对话框?

How to display custom dialog on application launch?

Sometimes I want to display a dialog when the app launches. For that purpose I created a custom dialog named LoginDialog and I am using an Application class java. However, I am having trouble showing this dialog. For one I cannot call getsupportfragmentmanager() or anything alike. Plus, the code replies that loginDialog has no show method which I thought was a standard operation of the AppCompatDialogFragment class. Any tips on how to solve this problem are appreciated!

The code:

public class ApplicationClass extends Application {
    
@Override
    public void onCreate() {
        super.onCreate();

        SharedPreferences sharedPreferences = getSharedPreferences("Settings", MODE_PRIVATE);
        SharedPreferences.Editor sEditor = sharedPreferences.edit();
        if (sharedPreferences.getInt("EmailVer", 0) == 5) {
            showDialog();
        }
        Log.i("Abertura", "onCreate fired");
    }
    private void showDialog() {
        LoginDialog loginDialog = new LoginDialog();
        loginDialog.show(get);
    }
}

也许尝试在 Activity class 中显示一个对话框?您可以加载 SharedPreferences 并检查您是否想在应用程序 class 中显示对话框,但在 Activity 中显示对话框。它看起来像这样:

应用类:

import android.app.Application;
import android.util.Log;

public class ApplicationClass extends Application
{
    private boolean showDialog;

    public boolean getShowDialog()
    {
        return showDialog;
    }

    @Override
    public void onCreate()
    {
        super.onCreate();
        Log.i("MyTag", "onCreate Application");

        // check if You want dialog. Main logic here
        showDialog = true;
    }
}

主要Activity:

import android.app.AlertDialog;
import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (((ApplicationClass) getApplication()).getShowDialog()) //get application and show dialog if `showDialog` is true
        {
            Log.i("MyTag", "Show dialog");
            new AlertDialog.Builder(this)
                    .setTitle("Title")
                    .setMessage("Message")
                    .show();
        }
        else
        {
            Log.i("MyTag", "Do not show dialog");
        }
    }
}