我在处理 Activity 中的 onCreate() 时遇到了一个主要问题。喜欢 thread说,我只能执行一次主要 Activity 的 onCreate() 方法中的部分代码。所以我按照该线程中的步骤进行了以下操作:
/*I've updated the code to SharePreferences version*/
public class MyApp extends Activity {
private static RMEFaceAppActivity instance;
private boolean wascalled = false;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//initiate some buttons here
sharedPreferences = this.getSharedPreferences("test",0);
editor = sharedPreferences.edit();
if(sharedPreferences.getString("wascalled", "false").equalsIgnoreCase("false"))
{
//work can only be done once
editor.putString("wascalled", "true");
editor.commit();
}
//set buttons to listener methods
}
void onClick(View arg0)
{
if(arg0.getId() == R.id.button1)
{
Intent intent = new Intent(this, MyChildApp.class);
startActivity(intent);
}
}
}
在 MyChildApp 类中,当工作完成时,我调用了 finish()
。但是,字段 wascalled
始终为 false。我认为当从 MyChildApp
返回时第二次执行 onCreate()
时,wascalled
应该已经设置为 true。然而事实并非如此。每次从MyChildApp
返回时,都会执行onCreate()
方法中if 语句中的代码。
有人对此有什么建议吗?非常感谢。
最佳答案
定义 SharedPreferences 并初始存储一个值 0/false
以表明 wascalled() 从未被调用。
现在,当第一次调用 wasCalled 时,将此 SharedPreference 变量的值更新为 1/true
。
下次当您的 onCreate()
运行时,检查 SharedPreference 中变量的值,如果值为 1/true,则不要再次执行它。
实现 SharedPreferences 的代码:
final String PREF_SETTINGS_FILE_NAME = "PrefSettingsFile";
int wasCalledValue;
onCreate() {
....
SharedPreferences preferences = getSharedPreferences(PREF_SETTINGS_FILE_NAME, MODE_PRIVATE);
wasCalledValue= preferences.getInt("value", 0);
if(wasCalledValue == 0)
{
// execute the code
//now update the variable in the SharedPreferences
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("value", 1);
editor.commit();
}
else if(wasCalledValue == 1)
{
//skip the code
}
} // end of onCreate()
关于android - 如何避免在 onCreate() 中执行部分代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11990827/