Android 仅当“活动”第一次打开时才运行代码

Android 仅当“活动”第一次打开时才运行代码,android,Android,在我正在制作的应用程序中,我希望一段代码仅在活动首次打开时运行 例如,我打开我的应用程序,然后第一次单击动物活动。此代码应该运行 stringListCounter = randInt(0, 100); 代码发生在这里: // What Happens When Activity Starts// @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceStat

在我正在制作的应用程序中,我希望一段代码仅在活动首次打开时运行

例如,我打开我的应用程序,然后第一次单击动物活动。此代码应该运行

stringListCounter = randInt(0, 100);
代码发生在这里:

// What Happens When Activity Starts//
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_animals);

    // What Number List Starts At//
    stringListCounter = randInt(0, 100);

    // Grab Audio And Convert//
    audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    // Link Button Team One to Activity_Animals//
    t1 = (Button) findViewById(R.id.Team1);
    t1.setEnabled(false);
    t1.setOnClickListener(this);

    // Link Button Number One to Activity_Animals//
    number1 = (TextView) findViewById(R.id.Number1);
    number1.setText(String.valueOf(Category.team_one));

    // Link Button Number Two to Activity_Animals//
    number2 = (TextView) findViewById(R.id.Number2);
    number2.setText(String.valueOf(Category.team_two));

    // Link Button Team Two to Activity_Animals//
    t2 = (Button) findViewById(R.id.Team2);
    t2.setEnabled(false);
    t2.setOnClickListener(this);

    // Link TextView Timer to Activity_Animals//
    Timer = (TextView) findViewById(R.id.Timer);

    // Link Button Next to Activity_Animals//
    next = (Button) findViewById(R.id.Next);
    next.setOnClickListener(this);

    // Link TextView Word to Activity_Animals//
    word = (TextView) findViewById(R.id.Word);

    // Create Media Player//
    mp = MediaPlayer.create(getApplicationContext(), R.raw.beep1);

    // Create Media Player 2//
    mp2 = MediaPlayer.create(getApplicationContext(), R.raw.gj);

}

然后从现在开始,在应用程序完全销毁之前,此代码不应运行。因此,基本上这段代码应该在每次打开应用程序时运行一次。这真的很难解释,所以如果你不明白,我试着用另一种方式解释谢谢

有一些方法可以实现这一点。例如,您可以将该代码放入应用程序扩展类的onCreate中,并在放入该整数的字段中创建一个getter/setter或一个公共字段(如果需要)

公共类MainApplication扩展了应用程序{ 公共字符串[]mStringListCounter; @凌驾 创建时的公共无效{ mStringListCounter=randinT0100; } } 然后在其他类中获得结果:

int stringListCounter = ((MainApplication)getApplication()).mStringListCounter;
编辑:当然,您必须在AndroidManifest.xml中声明您的应用程序活动名称:


将此代码放在OnCreate of activity中。如果存在此代码,则每次打开activity时都会运行此代码。我只想让那段代码运行一次。然后在应用程序再次完全打开之前不要运行
...
<application
    android:name=".MainApplication"
...