Mateo Mateo - 1 month ago 19
Android Question

Run Main Activity after Splash Screen

I am using a splash screen prior to starting my main activity. I currently have my splash screen coded by using the activity theme method as opposed to using the layout method. Everything in my code looks good in both the .java and .xml files (according to the software) because I have no errors yet every time I click the app icon in the emulator, it brings up the splash screen then the app exits without showing my main activity. Here's my code so far:

SplashActivity.java

package com.example.healthylife;

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

public class SplashActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);

Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}


MainActivity.java:

package com.example.healthylife;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}


Here's my manifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.healthylife" >

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >

<activity android:name=".SplashActivity"
android:label="@string/app_name"
android:theme="@style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>

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

<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>


Any advice would be greatly appreciated.

Answer

Two things:

  1. Only define the intent-filter once. (In your case the splash)
  2. Don't start your MainActivity right away. Add a delay, for example with a Handler. (Inside the onCreate of your Splash)

    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
             Intent intent = new Intent(SplashActivity.this,       MainActivity.class);
            startActivity(intent);
            finish();
        }
    }, 1000);