简体   繁体   中英

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);
    }
}

Maybe try to show a dialog in the Activity class? You can load SharedPreferences and check if You want to show a dialog in the Application class but show a dialog in Activity. It will look like this:

ApplicationClass:

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;
    }
}

MainActivity:

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");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM