How do I make a splash screen?

2018-12-31 01:50发布

I wanted to make my app look more professional, so I decided that I wanted to make a splash screen.

How would I create it and then implement it?

30条回答
零度萤火
2楼-- · 2018-12-31 02:03
public class SplashActivity extends Activity {

  Context ctx;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      ctx = this;
      setContentView(R.layout.activity_splash);

      Thread thread = new Thread(){
          public void run(){
              try {
                  sleep(3000);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }

              Intent in = new Intent(ctx,MainActivity.class);
              startActivity(in);
              finish();
          }
      };
      thread.start();
  }
}
查看更多
旧时光的记忆
3楼-- · 2018-12-31 02:06

you will not use a layout file. Instead, specify your splash screen’s background as the activity’s theme background. To do this, first create an XML drawable in res/drawable.

Note: all code below is available GitHub Link

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:drawable="@color/gray"/>

    <item>
        <bitmap
            android:gravity="center"
            android:src="@mipmap/ic_launcher"/>
    </item>

</layer-list>

Here, I’ve set up a background color and an image.

Next, you will set this as your splash activity’s background in the theme. Navigate to your styles.xml file and add a new theme for your splash activity:

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
    </style>

    <style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
        <item name="android:windowBackground">@drawable/background_splash</item>
    </style>

</resources>

In your new SplashTheme, set the window background attribute to your XML drawable. Configure this as your splash activity’s theme in your AndroidManifest.xml:

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

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

Finally, your SplashActivity class should just forward you along to your main activity:

public class SplashActivity extends AppCompatActivity {

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

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

Notice that you don’t even set up a view for this SplashActivity. The view comes from the theme. When you set up the UI for your splash activity in the theme, it is available immediately.

If you did have a layout file for your splash activity, that layout file would be visible to the user only after your app has been fully initialized, which is too late. You want the splash to be displayed only in that small amount of time before the app is initialized.

查看更多
墨雨无痕
4楼-- · 2018-12-31 02:07

Though there are good answers, I will show the google recommended way:

1)First create a Theme for splash screen: you have a theme called splashscreenTheme, your launcher theme would be:

<style name="splashscreenTheme">
  <item name="android:windowBackground">@drawable/launch_screen</item>
</style>

Note:

android:windowBackground already sets your splashscreen image no
need to do this in UI again.

you can also use color here instead of a drawable.

2)Set the theme to manifest of splashscreenActivity

   <activity
            android:name=".activity.splashscreenActivity"
            android:screenOrientation="portrait"
            android:theme="@style/splashscreenTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

3)make sure you launch_screen drawable is not in drawable folder if your image is not small.

It will result in faster launch screen start and save you from the black screen

It also avoids extra overdraw

查看更多
深知你不懂我心
5楼-- · 2018-12-31 02:09

Sometime user open the SplashActivity and quit immediately but the app still go to MainActivity after SPLASH_SCREEN_DISPLAY_LENGTH.

For prevent it: In SplashActivity you should check the SplashActivity is finishing or not before move to MainActivity

public class SplashActivity extends Activity {

    private final int SPLASH_SCREEN_DISPLAY_LENGTH = 2000;

    @Override
    public void onCreate(Bundle icicle) {
        ...
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                if (!isFinishing()) {//isFinishing(): If the activity is finishing, returns true; else returns false.
                    startActivity(new Intent(SplashActivity.this, MainActivity.class));
                    finish();
                }

            }, SPLASH_SCREEN_DISPLAY_LENGTH);
        }                             
   }                                
}

Hope this help

查看更多
倾城一夜雪
6楼-- · 2018-12-31 02:10

A Splash Screnn, by default, does not automatically make your Application look more professional. A professionally designed Splash Screen has a possibility of making your Application look more professional, but if you do not know how to write one then how professional will the rest of your Application actually be.

About the only reason (excuse) to have a Splash Screen is because you are doing a massive amount of Calculations or are waiting for GPS/WiFi to startup because your Application relies on that prior to it starting. Without the result of those Calculations or access to GPS/WiFi (etc.) your Application is dead in the water, thus you feel you need a Splash Screen, and MUST block the view of the Screen for any other running Programs (including the Background).

Such a Splash Screen ought to look like your Full Screen Application to give the impression that it has already initialized, then after the lengthy calculations are completed the final details could be filled in (the Image tweaked). The chance of that being the case or that it is the only way the Program could be designed is mighty small.

It would be better to allow the User (and the rest of the OS) to do something else while they wait rather than design your Program to be dependant on something that will take a while (when the duration of the wait is uncertain).

There are Icons on your Phone already that say that GPS/WiFi is starting. The time or space taken up by the Splash Screen could be spent loading pre-calculations or actually doing the Calculations. See the first Link below for the problems you create and what must be considered.

If you absolutely must wait for these Calculations or GPS/WiFi it would be best to simply let the Application start and have a pop-up that says that it is necessary to wait for the Calculations (a TEXTUAL "Initializing" Message is fine). The wait for GPS/WiFi is expected (if they were not enabled in another Program already) so announcing their wait times are unnecessary.

Remember that when the Splash Screen starts your Program IS actually running already, all you are doing is delaying the use of your Program and hogging the CPU/GPU to do something that most do not feel is necessary.

We had better really want to wait and see your Splash Screen every time we start your Program or WE will not feel it is very professionally written. Making the Splash Screen FULL Screen and a duplicate of the actual Program's Screen (so we think it is initialized when in fact it has not) MIGHT accomplish your goal (of making your Program look more professional) but I would not bet much on that.

Why not to do it: http://cyrilmottier.com/2012/05/03/splash-screens-are-evil-dont-use-them/

How to do it: https://encrypted.google.com/search?q=Android+splash+screen+source

So there is a good reason not to do it but IF you are certain that somehow your situation falls outside those examples then the means to do it is given above. Be certain that it really does make your Application look more professional or you have defeated the only reason you gave for doing this.

It is like a YouTube Channel that starts every Video with a lengthy Graphic Intro (and Outro) or feels the need to tell a Joke or explain what happened during the past week (when it is not a Comedy or LifeStyles Channel). Just show the show ! (Just run the Program).

查看更多
浪荡孟婆
7楼-- · 2018-12-31 02:11

After Android Marshmallow, other Productive use of Splash screen I come to think of is requesting necessary Android Permissions in your app's splash screen.

it seems like most apps handle permission request this way.

  • Dialogs make bad UIX and they break the main flow and make you decide on runtime and truth is most users might not even care if your app want to write something on SD card. Some of them might not even understand what we are trying to convey until we translate it in plain english.

  • Requesting permissions at one time make less number of "if else" before every operation and make your code looks clutter free.

This is a example of how you can ask for permissions in your splash activity for device running Android OS 23+ .

If all permissions are granted OR already granted OR app is running on Pre Marshmallow THEN just go and display main contents with little delay of half second so that user can appreciate effort we had put in reading this question and trying to give our best.

import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

import com.c2h5oh.beer.R;
import com.c2h5oh.beer.utils.Animatrix;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SplashActivity extends AppCompatActivity {

    final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;

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

        //show animations 
        Animatrix.scale(findViewById(R.id.title_play), 100);
        Animatrix.scale(findViewById(R.id.title_edit), 100);
        Animatrix.scale(findViewById(R.id.title_record), 100);
        Animatrix.scale(findViewById(R.id.title_share), 100);

        if (Build.VERSION.SDK_INT >= 23) {

            // Marshmallow+ Permission APIs
            fuckMarshMallow();

        } else {

            // Pre-Marshmallow
            ///Display main contents
            displaySplashScreen();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS: {
                Map<String, Integer> perms = new HashMap<String, Integer>();
                // Initial
                perms.put(Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
                perms.put(Manifest.permission.RECORD_AUDIO, PackageManager.PERMISSION_GRANTED);
                perms.put(Manifest.permission.MODIFY_AUDIO_SETTINGS, PackageManager.PERMISSION_GRANTED);
                perms.put(Manifest.permission.VIBRATE, PackageManager.PERMISSION_GRANTED);
                // Fill with results
                for (int i = 0; i < permissions.length; i++)
                    perms.put(permissions[i], grantResults[i]);

                // Check for ACCESS_FINE_LOCATION
                if (perms.get(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.MODIFY_AUDIO_SETTINGS) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.VIBRATE) == PackageManager.PERMISSION_GRANTED) {
                    // All Permissions Granted

                    // Permission Denied
                    Toast.makeText(SplashActivity.this, "All Permission GRANTED !! Thank You :)", Toast.LENGTH_SHORT)
                            .show();

                    displaySplashScreen();

                } else {
                    // Permission Denied
                    Toast.makeText(SplashActivity.this, "One or More Permissions are DENIED Exiting App :(", Toast.LENGTH_SHORT)
                            .show();

                    finish();
                }
            }
            break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }


    @TargetApi(Build.VERSION_CODES.M)
    private void fuckMarshMallow() {
        List<String> permissionsNeeded = new ArrayList<String>();

        final List<String> permissionsList = new ArrayList<String>();
        if (!addPermission(permissionsList, Manifest.permission.READ_EXTERNAL_STORAGE))
            permissionsNeeded.add("Read SD Card");
        if (!addPermission(permissionsList, Manifest.permission.RECORD_AUDIO))
            permissionsNeeded.add("Record Audio");
        if (!addPermission(permissionsList, Manifest.permission.MODIFY_AUDIO_SETTINGS))
            permissionsNeeded.add("Equilizer");
        if (!addPermission(permissionsList, Manifest.permission.VIBRATE))
            permissionsNeeded.add("Vibrate");

        if (permissionsList.size() > 0) {
            if (permissionsNeeded.size() > 0) {

                // Need Rationale
                String message = "App need access to " + permissionsNeeded.get(0);

                for (int i = 1; i < permissionsNeeded.size(); i++)
                    message = message + ", " + permissionsNeeded.get(i);

                showMessageOKCancel(message,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                                        REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
                            }
                        });
                return;
            }
            requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                    REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
            return;
        }

        Toast.makeText(SplashActivity.this, "No new Permission Required- Launching App .You are Awesome!!", Toast.LENGTH_SHORT)
                .show();

        displaySplashScreen();
    }


    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(SplashActivity.this)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", null)
                .create()
                .show();
    }

    @TargetApi(Build.VERSION_CODES.M)
    private boolean addPermission(List<String> permissionsList, String permission) {

        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
            permissionsList.add(permission);
            // Check for Rationale Option
            if (!shouldShowRequestPermissionRationale(permission))
                return false;
        }
        return true;
    }

    /**
     * Display main content with little delay just so that user can see
     * efforts I put to make this page
     */
    private void displaySplashScreen() {
        new Handler().postDelayed(new Runnable() {

        /*
         * Showing splash screen with a timer. This will be useful when you
         * want to show case your app logo / company
         */

            @Override
            public void run() {
                startActivity(new Intent(SplashActivity.this, AudioPlayerActivity.class));
                finish();
            }
        }, 500);
    }


}
查看更多
登录 后发表回答