仅在第一次应用程序启动时执行代码

时间:2014-05-05 15:35:38

标签: java android eclipse

我想仅在第一个应用程序午餐中执行特定命令,当用户再次打开应用程序时,将执行另一个命令。这是一个例子

if (this_is_first_lunch == true){
Toast.makeText(getApplicationContext(), "First time to open the app", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Not the first time to open it", Toast.LENGTH_SHORT).show();
}

我的问题是我应该写什么而不是“this_is_first_lunch”来使这段代码有效?

4 个答案:

答案 0 :(得分:4)

使用SharedPreferences。您应该在执行“第一次”代码后存储密钥,并在后续执行时进行检查。

答案 1 :(得分:2)

像这样使用共享偏好

private static String KEY_FIRST_RUN = "";
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    sharedPreferences = getPreferences(MODE_PRIVATE);

    if (!sharedPreferences.contains("KEY_FIRST_RUN")) {
        KEY_FIRST_RUN = "something";
        Log.d("First", "First run!");
    } else {
        Log.d("Second...", "Second run...!");
    }

    editor = sharedPreferences.edit();
    editor.putString("KEY_FIRST_RUN", KEY_FIRST_RUN);
    editor.commit();
}

答案 2 :(得分:2)

您可以使用“共享首选项”附加持久值,您可以在每次程序启动时读取该值。启动应用程序时,请检查是否已设置此变量。使用它来确定要执行的代码,然后设置变量以防止下次运行时再次发生。

boolean firstRun = getSharedPreferences("preferences", MODE_PRIVATE).getBoolean("firstrun", true);
if(firstRun){
    //set the firstrun to false so the next run can see it.
    getSharedPreferences("preferences", MODE_PRIVATE).edit().putBoolean("firstrun", false).commit();
    Toast.makeText(getApplicationContext(), "First time to open the app", Toast.LENGTH_SHORT).show();
}
else{
    Toast.makeText(getApplicationContext(), "Not the first time to open it", Toast.LENGTH_SHORT).show();
}

答案 3 :(得分:0)

你需要坚持,之前推出的应用程序......以下是关于如何通常持久保存数据的Android开发指南: http://developer.android.com/guide/topics/data/data-storage.html

在坚持第一个 a unch后,您可以检查该标志或您持久识别的任何内容...... 请记住,这需要应用程序在每次启动时读取该标志,这可能不会减慢速度,但可以叠加更多此类Activity并影响应用程序的启动性能......

相关问题