应用程序第一次启动时,对话窗口将打开

时间:2015-02-02 14:11:19

标签: java android

我创建了一个Dialog,每次用户打开App时都会打开。由于这可能会非常快速地惹恼用户,我想在第一次启动应用程序时打开它,然后才开始。

我试过以下:

public boolean openDialog = true;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (openDialog) {
        launchDialog();
    }
}

private void launchDialog() {
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
            context);

    // set title
    alertDialogBuilder.setTitle("Your Title");

    // set dialog message
    alertDialogBuilder
            .setMessage("Click yes to exit!")
            .setCancelable(false)
            .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int id) {
                    //don't open Dialog by next launch
                    openDialog = false;

                    // if this button is clicked, close
                    // current activity
                    MainActivity.this.finish();
                }
            })
            .setNegativeButton("No",new    DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int id) {
                    // if this button is clicked, just close
                    // the dialog box and do nothing
                    dialog.cancel();
                }
            });

    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();

    // show it
    alertDialog.show();
}

感谢您的帮助

阿德里安

3 个答案:

答案 0 :(得分:3)

您可以使用简单的sharedPreferences:

 private SharedPreferences mPrefs;
 private Editor mEditor;

初​​始化:

 mPrefs  = PreferenceManager.getDefaultSharedPreferences(context);
 mEditor = mPrefs.edit();

然后当对话框第一次出现时,保存状态,例如:

mEditor.putBoolean(FIRST_TIME_USED_KEY,true);
mEditor.commit();

当应用程序再次打开时,首先询问对话框是否已打开:

boolean isUsedBefore = mPrefs.getBoolean(FIRST_TIME_USED_KEY,false);

 if(isUsedBefore==true){
   //do nothing
 }else{
  dialog.show();
  }

FIRST_TIME_USED_KEY应该是存储在strings.xml中的字符串。

答案 1 :(得分:1)

实现这一目标的方法有多种。

方法1: Use of shared preference每当用户第一次打开时,都会在共享首选项中设置状态,并在每次需要显示对话框时进行检查。

注意:@Opiatefuchs提到同样的事情。

方法2:

Use database。这是第一次更新状态。如果对话框需要显示,则下次检查数据库。

基本上两种方法都以类似的方式工作。选择你最好的。

答案 2 :(得分:0)

将openDialog变量设为静态,使其位于类的范围内而不是实例:

public static boolean openDialog = true;

为获得最佳用户体验,您可以显示对话框:

1。每个时间间隔(例如:2天) 2。每次运行应用程序(每5次)。

您可以将这两个因素结合起来,您可以使用shared preferences类在偏好设置中保存一些值。

相关问题