安装后仅启动一次 activity

Launch an activity only once after Install

我有二维码扫描器应用程序。应用程序中有 3 个活动。

1) Main activity - 打开相机并开始扫描的按钮

2) QR activity - 扫描二维码

3) 网页 Activity - 成功扫描后,在应用程序中打开一个网页

在这里,Main activity 和 QR activity 应该只启动一次,只有在初始安装之后。我在某处读到有关使用共享首选项的信息。但是我对在哪里检查变量有点困惑,比如 activity。我应该检查 Main Activity 中的共享变量吗?

这是我的第一个应用程序。对不起,如果这是一个愚蠢的疑问。

没错,你必须用SharedPreferences来做。

Here is a good explaination about how to use them

在显示的第一个 activity 中,您必须在 onCreate 方法中添加这些行:

//this retrieve the sharedpreference element
SharedPreference myPref = this.getSharedPreferences(
  "prefName", Context.MODE_PRIVATE);
//this retrieve the boolean "firstRun", if it doesn't exists, it places "true"
var firstLaunch = myPref.getBoolean("firstLaunch", true);
//so, if it's not the first run do stuffs
if(!firstLaunch){
  //start the next activity
  finish();
}      
//else, if it's the first run, add the sharedPref
myPref.edit().putBoolean("firstLaunch", false).commit();

希望这对您有所帮助

要完成@Pier Giorgio Misley 的回答,您可以将 "firstLaunch" 检查放在 Main Activity 上,或者将其放在另一个 "splash" activity

要将它放在主要 activity 中,只需将 ui 设置为某种中性色,直到您决定是否应该完成 activity 并启动 Web Activity或显示主要 Activity 逻辑

或者,您可以创建一个 "splash" 屏幕,它可以充当桥梁 activity(显示一些徽标或漂亮的背景颜色),检查变量并决定哪个 activity 打开 Android splash

正如码头所说,保存它已经看过一次是要走的路。但是,我发现在一些旧设备上,共享首选项并不可靠!

我建议改用 SQLite 数据库。

创建一个table如下

TABLE NAME: SEEN_ACTIVITY
Column 1: ID INT PRIMARY KEY
Column 2: SEEN VARCHAR

然后,activity 启动后,检查 SEEN_ACTIVITY 中是否有 id = '0' 的记录。如果不是,则插入一个如下,(0, true).

然后,每次应用程序启动时,检查记录是否存在 (0, true)。如果没有,启动额外的 activity.

My MainActivity.java

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

    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            SharedPreferences settings = getSharedPreferences("prefName",MODE_PRIVATE);
            boolean firstLaunch = settings.getBoolean("firstLaunch", true);
            if(firstLaunch == false) {
                SharedPreferences.Editor editor=settings.edit();
                editor.putBoolean("firstRun",true);
                editor.commit();
                Intent i = new Intent(SplashActivity.this, MainActivity.class);
                startActivity(i);
                finish();
            }
            else {
                Intent i = new Intent(SplashActivity.this, ScannerActivity.class);
                startActivity(i);
                finish();
            }
        }
    }, SPLASH_TIME_OUT);
}

在新的 Splash 中编写此代码 Activity