Android 运行 一次 class 一次 Activity

Android running a class only once on an Activity

我写了一个 class 并且只希望它在 activity 中 运行 一次。

所以当 activity 恢复时,这个 class 将不再有任何效果,另一个 class 将生效。

所以可以说,在首次启动 ACTIVITY 时,而不是应用程序,它将执行 class,而在其他每次启动时,它都会执行其他操作。如果应用程序关闭并重新进入,它会记住 class 已经 运行 并且不会这样做。

我希望这一切都有意义!

这是 class 我只想 运行 一次:

//Should only happen on first launch of activity.
    public void AgeCalculation() {

            if (male == true && age >= 18) {
                newweight = (weight * 0.8);
            }
            weightresultText.setText(Double.toString(newweight));
            //Saves Weight to sharedpreference to use later.
            SaveWeight();
        }

这是每隔一段时间 运行 的 class:

    //runs on every other launch of activity

        public void AfterFirstLaunch(){
//The button clicks get the saved value and increments it and saves it again.
            buttonClick1();
            buttonClick2();
            buttonClick3();
            buttonClick4();
            buttonClick5();

            //receive value on other launches and show on field.

            SharedPreferences shoulderPreference = getApplicationContext().getSharedPreferences("ShoulderWeightPreference", Context.MODE_PRIVATE);
            String newweight =  shoulderPreference.getString("storednewweight", "");
            weightresultText.setText(newweight);
        }

您应该看看 developper 网站,因为 android 那里解释了一切。

所以你会有类似的东西:

protected void onCreate() {
    AgeCalculation();
    super.onCreate(); //since we overridden it we want it to run too.
}

protected void onResume() { //it could be on start depending on what you want
    AfterFirstLaunch();
    super.onResume();
}

在 Activity 中有一个名为 onCreate() 的继承方法,每当创建 Activity 时都会调用该方法。

为了检查Activity是否已经运行ning,在onCreate()方法中你可以检查传入的参数Bundle savedInstanceState是否为null .

在 Activity 的第一个 运行 上,savedInstanceState 将为空。任何后续的 "creations" 都会使 savedInstanceState NOT null 因为它已经创建了。

因此,为了获得您正在寻找的结果,您需要这样的东西:

@Override
protected void onCreate(Bundle savedInstanceState) {
    if(savedInstanceState == null) {
        // The Activity is brand new
        AgeCalculation();
    }
    else {
        // The Activity has been re-created
        AfterFirstLaunch();
    }

    // ... Other stuff
}

顺便说一句,你说你想要 运行 这些不同的 "classes" 但我假设你是指方法?

编辑:如果我错了请纠正我,但我认为您只需要在第一个 运行 上填写共享首选项?

如果是这种情况,那么您只需要像这样检查您的共享偏好是否存在:

@Override
protected void onCreate(Bundle savedInstanceState) {
    SharedPreferences shoulderPreference = getApplicationContext().getSharedPreferences("ShoulderWeightPreference", Context.MODE_PRIVATE);

    // The second parameter in getString() is the default value which
    // is returned if the prefernece "storednewweight" does not
    // exist (yet)
    String prefValue =  shoulderPreference.getString("storednewweight", "");

    if(prefValue.equals("")) {
        // The preference was not created before
        AgeCalculation();
    }
    else {
        // Preference already created
        AfterFirstLaunch();
    }

    // ... Other stuff
}