Search code examples
androidandroid-activityshowlauncher

Showing launcher screen only once in Android


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;

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