Monday, April 15, 2013

Create a Splash Screen

A splash screen is an image that appears while a game or program is loading. It may also be used to describe an introduction page on a website. Splash screens cover the entire screen or simply a rectangle near the center of the screen. The splash screens of operating systems and some applications that expect to be run full-screen usually cover the entire screen. Today's tutorial is about how to create a splash screen for your Android application.

First of all, we need to create the layout of the Activity that will present our splash screen. All we need to do is to define a layout with an image that will cover the entire screen. The splash_screen.xml file is shown below:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<ImageView android:id="@+id/splash_screen"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="@drawable/stadium"
android:layout_gravity="center"/>

</LinearLayout>
Then we need to write the code that will display the splash screen for a short period and then navigate the user to the main screen of our application. The code of the SplashScreenActivity is quoted below:
package com.androidsnippet.SplashScreen;

import java.util.Timer;
import java.util.TimerTask;

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

public class SplashScreenActivity extends Activity {

private int mSplashTime = 4000;
private Timer mTimer;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);

mTimer = new Timer();
mTimer.schedule(
new TimerTask() {
public void run() {
finish();
Intent intent = new Intent(getApplicationContext(), MainScreen.class);
startActivity(intent);
}
},
mSplashTime);
}
}
We define a Timer and set it to run for 4 seconds. During this time our splash screen is displayed. After 4 seconds have passed we finish the SplashScreenActivity and start the MainScreen of our application. Instead of just waiting an amount of seconds without doing anything you may want to schedule a task to run that will load some resources needed by your application. In this occasion the splash screen may be displayed for as long as the task is executing. If you run the project on your Android emulator you should see something like this when the application starts:
This is it! Find the project here! Cheers!