如何仅在首次运行应用程序时显示警告对话框?

waa*_*990 9 java android android-alertdialog

我有一个警告,我想在第一次启动应用程序后第一次显示.

我怎样才能做到这一点?

Bri*_*ley 22

有几种方法可以做到这一点,但也许最简单的方法是检查SharedPreferences对象中的标志,并在显示警报后设置它.

SharedPreferences

就像是

public class MyActivity extends Activity {

public static final String PREFS_NAME = "MyPrefsFile";

@Override
protected void onCreate(Bundle state){

   super.onCreate(state);
   SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
   boolean dialogShown = settings.getBoolean("dialogShown", false);

   if (!dialogShown) {
     // AlertDialog code here

     SharedPreferences.Editor editor = settings.edit();
     editor.putBoolean("dialogShown", true);
     editor.commit();    
   }
}
Run Code Online (Sandbox Code Playgroud)