只有在第一次打开活动时才会运行代码

时间:2015-01-18 16:18:08

标签: android

在我正在创建的应用程序中,我只想在首次打开活动时运行一段代码。

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

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

}

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

1 个答案:

答案 0 :(得分:0)

有一些方法可以实现这一目标。例如,您可以将该代码放在Application扩展类的onCreate中,并将getter / setter(或者如果需要,一个公共字段)放到放置该整数的字段中。

public class MainApplication extends Application {
    public String[] mStringListCounter;

    @Override
    public void onCreate() {
        mStringListCounter = randInt(0, 100);
    }
}

然后将结果导入其他类:

int stringListCounter = ((MainApplication)getApplication()).mStringListCounter;

编辑:当然,您必须在AndroidManifest.xml中声明您的应用活动名称:

...
<application
    android:name=".MainApplication"
...
相关问题