简体   繁体   中英

Run Activity only by first start

I just want to start a activity on the first run. So after I run it once it should never open again.This Activity is added with

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

so this Activity starts first. I have a variable which helps me to decide if this Activity started for the first time or not (Im saving it with SharedPreferences which is called sem_first_time).When it is 0 then its the first time if not then this Activity have to finish and start another one. Here's my code

@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);

I got a Button which sets first_start to 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);

    ...
}

But when I start this App once It is showing this Activity again ... What is wrong ?

It is happening because this is the Launcher activity and you are finishing the activity before launching the other activity . It should be like

if (first_start == 1)
{

    Intent start = new Intent(this, Main.class);
    startActivity(start);
    finish();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM