仅在第一次启动时运行活动

时间:2014-08-29 21:13:35

标签: java android

我只是想在第一次运行时开始一项活动。所以在我运行之后它应该永远不会再打开。此活动添加了

<intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

所以此活动首先开始。 我有一个变量可以帮助我决定这个Activity是否第一次启动(我用SharedPreferences保存它,称为sem_first_time)。当它为0时它是第一次,如果没有那么这个Activity必须完成并启动另一个。 这是我的代码

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    SharedPreferences data = getSharedPreferences("datas",Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = data.edit();

    first_start = data.getInt("fstart", 0);

    if (first_start == 1)
    {
        finish();
        Intent start = new Intent(this, Main.class);
        startActivity(start);
    }

    setContentView(R.layout.first_start);

我有一个Button,它将first_start设置为1

public void create (View view)
{
    SharedPreferences data = getSharedPreferences("datas",Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = data.edit();

    first_start = 1;
    editor.putInt("fstart", first_start);

    ...
}

但是,当我再次显示此活动时,我启动此应用程序......出了什么问题?

1 个答案:

答案 0 :(得分:0)

这种情况正在发生,因为这是Launcher活动,您在启动其他活动之前正在完成活动。它应该像

if (first_start == 1)
{

    Intent start = new Intent(this, Main.class);
    startActivity(start);
    finish();
}
相关问题