My Profile Photo

Andrea Maglie


Software Engineer, guitar player. Founder of GDG (Google Developer Group) Venice.


A simple splash screen in Android

Splash screens are not so popular in Android development. But wait: now Google started to put splash screens in its apps??? Take a look at Google Drive app for example. Does it mean that now we have a new standard?

This is not the right post to talk about if splash screen in Android is good or bad. Let’s think only about code: implementing a splash screen is easy.

I’ve seen many splash screen implementations, but some of them have one common bug. If I close the app (aka: press back button) when the splah screen is visibile, after a while the main screen of the app appears. WTF??? I’ve closed you, why are you coming back again?

The trick is very simple. Let’s take a look at how a very simple SplashActivity could be:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public class SplashActivity extends Activity {

    private static int SPLASH_TIME_OUT = 2000; // 2 seconds

    private Handler mHandler;

    private Runnable mRunnable = new Runnable() {

        @Override
        public void run() {
            startMainActivity();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_splash);

        mHandler = new Handler();
    }

    @Override
    protected void onResume() {
        super.onResume();

        mHandler.postDelayed(mRunnable, SPLASH_TIME_OUT);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

        removeCallbacks();
    }

    @Override
    protected void onStop() {
        super.onStop();

        removeCallbacks();
    }

    private void removeCallbacks() {
        if (mHandler != null) {
            mHandler.removeCallbacks(mRunnable);
        }
    }

    private void startMainActivity() {
        startActivity(new Intent(this, MainActivity.class));

        finish();
    }
}

This is very straightforward. The key point here is the removeCallbacks method: this is where I’m assuring that MainActivity is not started if the user have pressed back button (explicitly closing the application) or if app has gone in background.

In your AndroidManifest.xml don’t forget to declare your activity with the following attributes:

<activity
    android:name=".SplashActivity"
    android:configChanges="orientation|keyboardHidden"
    android:label="@string/application_name"
    android:noHistory="true" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
comments powered by Disqus