【发布时间】:2016-03-25 06:23:02
【问题描述】:
我有一段代码,我只想在第一次调用特定的 OnCreate() 方法时运行(每个应用会话),而不是每次创建活动时运行。有没有办法在 Android 中做到这一点?
【问题讨论】:
标签: android android-studio android-lifecycle oncreate
我有一段代码,我只想在第一次调用特定的 OnCreate() 方法时运行(每个应用会话),而不是每次创建活动时运行。有没有办法在 Android 中做到这一点?
【问题讨论】:
标签: android android-studio android-lifecycle oncreate
protected void onCreate(Bundle savedInstanceState) 拥有你所需要的一切。
如果savedInstanceState == null 则为第一次。
因此您不需要引入额外的 -static- 变量。
【讨论】:
在您的活动中使用静态变量,如下所示
private static boolean DpisrunOnce=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_run_once);
if (DpisrunOnce){
Toast.makeText(getApplicationContext(), "already runned", Toast.LENGTH_LONG).show();
//is already run not run again
}else{
//not run do yor work here
Toast.makeText(getApplicationContext(), "not runned", Toast.LENGTH_LONG).show();
DpisrunOnce =true;
}
}
【讨论】:
使用static 变量。
static boolean checkFirstTime;
【讨论】:
使用 sharedpreference...第一次将值设置为 true...在每次运行时检查值是否设置为 true...并根据代码执行代码
例如
SharedPreferences preferences = getSharedPreferences("MyPrefrence", MODE_PRIVATE);
if (!preferences.getBoolean("isFirstTime", false)) {
//your code goes here
final SharedPreferences pref = getSharedPreferences("MyPrefrence", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("isFirstTime", true);
editor.commit();
}
【讨论】: