Search code examples
androidsplash-screen

Splash screen not opening first


Instead of opening the splash screen first, it opens the main activity then the splash screen.What might be be the problem.The splash screen wont go away until i press back button.

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.content.Intent;
import android.os.Handler;

public class MainActivity extends AppCompatActivity {
  private static int SPLASH_TIME_OUT=4000;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  new Handler().postDelayed(new Runnable(){
     public void run(){
     Intent homeIntent=new Intent(MainActivity.this,Splash.class);
     startActivity(homeIntent);
     finish();
     }
        }, SPLASH_TIME_OUT);
   }
}

Solution

  • In AndroidManifest.xml,

    <activity
        android:name=".SplashActivity"
        android:noHistory="true"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar.FullScreen">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
    
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".MainActivity"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar.FullScreen" />
    

    And in the splashscreen.java onCreate function, you can set up a timer to call mainactivity

    new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    startActivity(new Intent(getApplicationContext(), MainActivity.class));
                }
            },4000);
    

    Hope this helps