gpt4 book ai didi

java - Android 在一个 Activity 上只运行一次类

转载 作者:行者123 更新时间:2023-12-01 11:56:25 24 4
gpt4 key购买 nike

我编写了一个类,只希望它在该 Activity 中运行一次。

因此,当 Activity 恢复时,该类将不再产生任何影响,而另一个类将生效。

因此,假设在第一次启动 ACTIVITY(而不是应用程序)时,它将执行该类,并且在每次其他启动时,它将执行其他操作。如果应用程序关闭并重新进入,它会记住该类已经运行并且不会执行它。

我希望这一切都有道理!

这是我只想运行一次的类:

//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();
}

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

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

最佳答案

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

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

在 Activity 首次运行时,savedInstanceState 将为 null。任何后续的“创建”都会使 savedInstanceState 不为 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
}

顺便说一句,您说您想运行这些不同的“类”,但我认为您指的是方法?

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

如果是这种情况,那么您只需检查您的共享首选项是否存在,如下所示:

@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
}

关于java - Android 在一个 Activity 上只运行一次类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28417710/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com