Question

I want to show launcher screen in Android app only once. Then if the user is on the second screen, if he presses back button, I want app to close. What's wrong in this code? The first screen shows again, what mustn't be.

public class MainActivity extends Activity {

    private boolean firstscreenshown=false; 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (firstscreenshown==true) finish();
        firstscreenshown=true;

or

public class MainActivity extends Activity {

    private boolean firstscreenshown; 

    public MainActivity() {
        this.firstscreenshown = false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (firstscreenshown==true) finish();
        firstscreenshown=true;
Was it helpful?

Solution

Use this code for handle back button in your MainActivity class:

@Override
    public void onBackPressed()
        {
            // TODO Auto-generated method stub
            super.onBackPressed();
            Intent startMain = new Intent(Intent.ACTION_MAIN);
            startMain.addCategory(Intent.CATEGORY_HOME);
            startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(startMain);
        }

OTHER TIPS

I have a disclaimer view that I display the first time my app is run. Here is how I handle it:

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // check preferences to see if disclaimer has been display
    boolean showDisclaimer = getPreferences(MODE_PRIVATE).getBoolean("disclaimer", true);
    if (showDisclaimer) {

        // turn off the disclaimer
        getPreferences(MODE_PRIVATE).edit().putBoolean("disclaimer",false).commit();

        // display the disclaimer
        Intent intent = new Intent(MainActivity.this, LegalActivity.class);
        startActivity(intent);
    }

    setContentView(R.layout.activity_main);
}

Here is the activity for the disclaimer:

public class LegalActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.legal_detail);

    // Watch for guide button clicks.
    Button button = (Button) this.findViewById(R.id.legal_button);
    button.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            finish();
        }
    });
}

My disclaimer view has a done button which closes it.

Hope this helps!

Call finish after your call to the second activity, so when the second screen appears the previous one will be erased.

startActivity(intent)

The best and simplest way to achieve this would be to override onPause() method and call :

finish();

inside the first activity!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top