'Why doesn't the finish() method work on my android studio project? 1

I'm trying to create a Splash screen and that was successful. However, I want the splash screen to disappear after 3 seconds. In an attempt to achieve this, I used the finish() method which didn't work to any avail. I'm wondering why the finish() method is not working on my app and what I can do to make the Splash Screen disappear in 3 seconds.All help would be greatly appreciated.

   package com.pace.carryonsplashpage;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class SplashScreenActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // setContentView(R.layout.activity_splash_screen);
        Intent I = new Intent(SplashScreenActivity.this, MainActivity.class);
        startActivity(I);
            finish();
    }


}

Home Activity XML code

    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".HomeActivity">

</androidx.constraintlayout.widget.ConstraintLayout>


Solution 1:[1]

Did you try this code? It will close the SplashActivity after 3 seconds.

new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent i=new Intent(MainActivity.this,
                                         SecondActivity.class);
                //Intent is used to switch from one activity to another.
                  
                startActivity(i);
                //invoke the SecondActivity.
                  
                finish();
                //the current activity will get finished.
            }
        }, 3000); // 3 seconds

Also don't comment the setContentView(). You want see anything on the screen without it

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1