Wednesday 2 May 2012

How to make a basic splash screen

The following code will show you how to create a basic splashscreen for your Android application that will stay for 5 seconds. If we don't want to wait we can tap the screen to go directly to the next Activity. Source project is on the bottom of the tutorial.
Lets go through the code to see how simple it is to make a very basic splash screen for your application.
The splashscreen will be the startup Activity for our application and on application launch a Thread will start that will listen for touch events.
01public class SplashScreen extends Activity {
02
03    //how long until we go to the next activity
04    protected int _splashTime = 5000;
05
06    private Thread splashTread;
07
08    /** Called when the activity is first created. */
09    @Override
10    public void onCreate(Bundle savedInstanceState) {
11        super.onCreate(savedInstanceState);
12        setContentView(R.layout.splash);
13
14        final SplashScreen sPlashScreen = this;
15
16        // thread for displaying the SplashScreen
17        splashTread = new Thread() {
18            @Override
19            public void run() {
20                try {
21                    synchronized(this){
22
23                        //wait 5 sec
24                        wait(_splashTime);
25                    }
26
27                catch(InterruptedException e) {}
28                finally {
29                    finish();
30
31                    //start a new activity
32                    Intent i = new Intent();
33                    i.setClass(sPlashScreen, Main.class);
34                    startActivity(i);
35
36                    stop();
37                }
38            }
39        };
40
41        splashTread.start();
42    }
43
44    //Function that will handle the touch
45    @Override
46    public boolean onTouchEvent(MotionEvent event) {
47        if (event.getAction() == MotionEvent.ACTION_DOWN) {
48            synchronized(splashTread){
49                splashTread.notifyAll();
50            }
51        }
52        return true;
53    }
54
55}

No comments:

Post a Comment