如何制作启动画面?

发布于 2024-10-27 23:46:43 字数 1436 浏览 5 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

零崎曲识 2024-11-03 23:46:43

请注意,此解决方案不会让用户等待更多时间:启动屏幕的延迟取决于应用程序的启动时间。

当你打开任何 Android 应用程序时,默认情况下你会看到一个黑色的屏幕,顶部有应用程序的标题和图标,你可以使用样式/主题来更改它。

首先,在values文件夹中创建一个style.xml并为其添加样式。

<style name="splashScreenTheme" parent="@android:style/Theme.DeviceDefault.Light.NoActionBar">
    <item name="android:windowBackground">@drawable/splash_screen</item>
</style>

您可以使用任何其他主题作为父主题,而不是使用 @android:style/Theme.DeviceDefault.Light.NoActionBar

其次,在您的应用 Manifest.xml 中将 android:theme="@style/splashScreenTheme" 添加到您的主要 Activity。

<activity
        android:name="MainActivity"
        android:label="@string/app_name"
        android:theme="@style/splashScreenTheme" >

第三,在 onCreate() 启动活动中更新您的主题。

protected void onCreate(Bundle savedInstanceState) {
    // Make sure this is before calling super.onCreate
    setTheme(R.style.mainAppTheme);
    super.onCreate(savedInstanceState);
}

更新
查看这篇文章

感谢@mat1h 和@adelriosantiago

Note this solution will not let the user wait more: the delay of the splash screen depends on the start up time of the application.

When you open any android app you will get by default a some what black screen with the title and icon of the app on top, you can change that by using a style/theme.

First, create a style.xml in values folder and add a style to it.

<style name="splashScreenTheme" parent="@android:style/Theme.DeviceDefault.Light.NoActionBar">
    <item name="android:windowBackground">@drawable/splash_screen</item>
</style>

Instead of using @android:style/Theme.DeviceDefault.Light.NoActionBar you can use any other theme as a parent.

Second, in your app Manifest.xml add android:theme="@style/splashScreenTheme" to your main activity.

<activity
        android:name="MainActivity"
        android:label="@string/app_name"
        android:theme="@style/splashScreenTheme" >

Third, Update your theme in your onCreate() launch activity.

protected void onCreate(Bundle savedInstanceState) {
    // Make sure this is before calling super.onCreate
    setTheme(R.style.mainAppTheme);
    super.onCreate(savedInstanceState);
}

UPDATE
Check out this post.

Thanks to @mat1h and @adelriosantiago

心碎的声音 2024-11-03 23:46:43

进一步阅读:

旧答案:

如何简单的启动屏幕

此答案向您展示了当您的应用程序出于品牌原因等原因启动时,如何在固定的时间内显示启动屏幕。例如,您可以选择显示启动屏幕 3 秒。但是,如果您想在不同的时间(例如应用程序启动时间)显示启动屏幕,您应该查看 Abdullah 的答案 https:/ /stackoverflow.com/a/15832037/401025。但请注意,应用程序在新设备上启动可能会非常快,因此用户只会看到闪烁,这是糟糕的用户体验。

首先,您需要在 layout.xml 文件中定义闪屏

  <?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical" android:layout_width="fill_parent"
          android:layout_height="fill_parent">

          <ImageView android:id="@+id/splashscreen" android:layout_width="wrap_content"
                  android:layout_height="fill_parent"
                  android:src="@drawable/splash"
                  android:layout_gravity="center"/>

          <TextView android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:text="Hello World, splash"/>

  </LinearLayout>

以及您的活动:

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

public class Splash extends Activity {

    /** Duration of wait **/
    private final int SPLASH_DISPLAY_LENGTH = 1000;

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

        /* New Handler to start the Menu-Activity 
         * and close this Splash-Screen after some seconds.*/
        new Handler().postDelayed(new Runnable(){
            @Override
            public void run() {
                /* Create an Intent that will start the Menu-Activity. */
                Intent mainIntent = new Intent(Splash.this,Menu.class);
                Splash.this.startActivity(mainIntent);
                Splash.this.finish();
            }
        }, SPLASH_DISPLAY_LENGTH);
    }
}

仅此而已;)

Further reading:

Old answer:

HOW TO: Simple splash screen

This answers shows you how to display a splash screen for a fixed amount of time when your app starts for e.g. branding reasons. E.g. you might choose to show the splash screen for 3 seconds. However if you want to show the spash screen for a variable amount of time (e.g. app startup time) you should check out Abdullah's answer https://stackoverflow.com/a/15832037/401025. However be aware that app startup might be very fast on new devices so the user will just see a flash which is bad UX.

First you need to define the spash screen in your layout.xml file

  <?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical" android:layout_width="fill_parent"
          android:layout_height="fill_parent">

          <ImageView android:id="@+id/splashscreen" android:layout_width="wrap_content"
                  android:layout_height="fill_parent"
                  android:src="@drawable/splash"
                  android:layout_gravity="center"/>

          <TextView android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:text="Hello World, splash"/>

  </LinearLayout>

And your activity:

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

public class Splash extends Activity {

    /** Duration of wait **/
    private final int SPLASH_DISPLAY_LENGTH = 1000;

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

        /* New Handler to start the Menu-Activity 
         * and close this Splash-Screen after some seconds.*/
        new Handler().postDelayed(new Runnable(){
            @Override
            public void run() {
                /* Create an Intent that will start the Menu-Activity. */
                Intent mainIntent = new Intent(Splash.this,Menu.class);
                Splash.this.startActivity(mainIntent);
                Splash.this.finish();
            }
        }, SPLASH_DISPLAY_LENGTH);
    }
}

Thats all ;)

囚我心虐我身 2024-11-03 23:46:43
  • 创建一个活动:Splash
  • 创建一个布局 XML 文件:splash.xml
  • 将 UI 组件放入splash.xml 布局中,使其看起来如您所愿
  • 您的 Splash.java 可能如下所示:

    public class Splash 扩展 Activity {
        @覆盖
        公共无效onCreate(捆绑保存实例状态){
            super.onCreate(savedInstanceState);
            setContentView(R.layout.splash);
    
            int 秒数延迟 = 1;
            new Handler().postDelayed(new Runnable() {
                    公共无效运行(){
                            startActivity(new Intent(Splash.this, ActivityB.class));
                            结束();
                    }
            }, 延迟秒数 * 1000);
        }
    }
    
  • ActivityB.class更改为你想要在启动屏幕后启动的任何活动

  • 检查您的清单文件,它应该看起来像

<前><代码> <活动
android:name=".HomeScreen"
android:label="@string/app_name">

<活动
android:name=".Splash"
android:label="@string/title_activity_splash_screen">
<意图过滤器>
<动作 android:name="android.intent.action.MAIN" />
<类别 android:name="android.intent.category.LAUNCHER" />

  • Create an activity: Splash
  • Create a layout XML file: splash.xml
  • Put UI components in the splash.xml layout so it looks how you want
  • your Splash.java may look like this:

    public class Splash extends Activity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.splash);
    
            int secondsDelayed = 1;
            new Handler().postDelayed(new Runnable() {
                    public void run() {
                            startActivity(new Intent(Splash.this, ActivityB.class));
                            finish();
                    }
            }, secondsDelayed * 1000);
        }
    }
    
  • change ActivityB.class to whichever activity you want to start after the splash screen

  • check your manifest file and it should look like

        <activity
            android:name=".HomeScreen"
            android:label="@string/app_name">     
        </activity>

        <activity
            android:name=".Splash"
            android:label="@string/title_activity_splash_screen">     
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
你曾走过我的故事 2024-11-03 23:46:43

上面的答案已经很好了,但是我还想补充一点。我是Android新手,在开发过程中遇到了这些问题。希望这可以帮助像我这样的人。

  1. 启动屏幕是我的应用程序的入口点,因此在 AndroidManifest.xml 中添加以下行。

    <前><代码> <活动
    android:name=".SplashActivity"
    android:theme="@android:style/Theme.DeviceDefault.Light.NoActionBar">
    <意图过滤器>
    <动作 android:name="android.intent.action.MAIN" />
    <类别 android:name="android.intent.category.LAUNCHER" />

  2. 启动画面在应用程序生命周期中应该只显示一次,我使用布尔变量来记录启动画面的状态,并且只在第一次显示。

    public class SplashActivity 扩展 Activity {
        私有静态布尔splashLoaded = false;
    
        @覆盖
        公共无效onCreate(捆绑保存实例状态){
            super.onCreate(savedInstanceState);
    
            如果(!splashLoaded){
                setContentView(R.layout.activity_splash);
                int 秒数延迟 = 1;
                new Handler().postDelayed(new Runnable() {
                    公共无效运行(){
                        startActivity(new Intent(SplashActivity.this, MainActivity.class));
                        结束();
                    }
                }, 延迟秒数 * 500);
    
                飞溅加载=真;
            }
            别的 {
                Intent goToMainActivity = new Intent(SplashActivity.this, MainActivity.class);
                goToMainActivity.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                启动活动(转到主活动);
                结束();
            }
        }
    }
    

快乐编码!

The answers above is very good, but I would like to add something else. I am new to Android, I met these problem during my development. hope this can help someone like me.

  1. The Splash screen is the entry point of my app, so add the following lines in AndroidManifest.xml.

        <activity
            android:name=".SplashActivity"
            android:theme="@android:style/Theme.DeviceDefault.Light.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    
  2. The splash screen should only show once in the app life cycle, I use a boolean variable to record the state of the splash screen, and only show it on the first time.

    public class SplashActivity extends Activity {
        private static boolean splashLoaded = false;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            if (!splashLoaded) {
                setContentView(R.layout.activity_splash);
                int secondsDelayed = 1;
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        startActivity(new Intent(SplashActivity.this, MainActivity.class));
                        finish();
                    }
                }, secondsDelayed * 500);
    
                splashLoaded = true;
            }
            else {
                Intent goToMainActivity = new Intent(SplashActivity.this, MainActivity.class);
                goToMainActivity.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                startActivity(goToMainActivity);
                finish();
            }
        }
    }
    

happy coding!

水染的天色ゝ 2024-11-03 23:46:43

阿卜杜拉的回答很好。但我想在我的答案中添加更多细节。

实现启动屏幕

以正确的方式实现启动屏幕与您想象的有些不同。您看到的启动视图必须立即准备就绪,甚至在您可以在启动活动中膨胀布局文件之前也是如此。

所以你不会使用布局文件。相反,请将启动屏幕的背景指定为活动的主题背景。为此,首先在 res/drawable 中创建一个 XML 可绘制对象。

background_splash.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Background Color -->
    <item
        android:drawable="@color/gray"/>

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

</layer-list>

它只是一个带有中心背景色徽标的图层列表。

现在打开 styles.xml 并添加此样式。

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

此主题将没有操作栏,并且具有我们上面刚刚创建的背景。

在清单中,您需要将 SplashTheme 设置为要用作启动画面的活动。

<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>

然后在您的活动代码中使用意图将用户导航到启动后的特定屏幕。

public class SplashActivity extends AppCompatActivity {

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

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

这才是正确的做法。我用这些参考资料来回答。

  1. https://material.google.com/patterns/launch-screens.html
  2. https://www.bignerdranch.com/blog/splash-屏幕正确方式/
    感谢这些人将我推向正确的方向。我想帮助其他人,因为接受的答案不建议执行启动屏幕。

Abdullah's answer is great. But i want to add some more details to it with my answer.

Implementing a Splash Screen

Implementing a splash screen the right way is a little different than you might imagine. The splash view that you see has to be ready immediately, even before you can inflate a layout file in your splash activity.

So 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.

background_splash.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Background Color -->
    <item
        android:drawable="@color/gray"/>

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

</layer-list>

It just a layerlist with logo in center background color with it.

Now open styles.xml and add this style

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

This theme will have no actionbar and with background that we just created above.

And in manifest you need to set SplashTheme to activity that you want to use as splash.

<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>

Then inside your activity code navigate user to the specific screen after splash using 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();
    }
}

That's the right way to do. I used these references for answer.

  1. https://material.google.com/patterns/launch-screens.html
  2. https://www.bignerdranch.com/blog/splash-screens-the-right-way/
    Thanks to these guys for pushing me into right direction. I want to help others because accepted answer isn't a recommended to do splash screen.
橘味果▽酱 2024-11-03 23:46:43
  1. 创建一个Activity SplashScreen.java

    public class SplashScreen 扩展 Activity {
    受保护的布尔_active = true;
    受保护的 int _splashTime = 3000; // 显示启动画面的时间(以毫秒为单位)
    
    
    
    @覆盖
    公共无效onCreate(捆绑保存实例状态){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splashscreen);
    
        线程splashTread = new Thread() {
            @覆盖
            公共无效运行(){
                尝试 {
                    int 等待 = 0;
                    while (_active && (等待 < _splashTime)) {
                        睡眠(100);
                        如果(_active){
                            等待+= 100;
                        }
                    }
                } catch (异常 e) {
    
                } 最后 {
    
                    启动活动(新意图(SplashScreen.this,
                            MainActivity.class));
                    结束();
                }
            };
                 };
        启动();
    }
     }
    
  2. splashscreen.xml 就像这样

    
    
     
    
  1. Create an Activity SplashScreen.java

    public class SplashScreen extends Activity {
    protected boolean _active = true;
    protected int _splashTime = 3000; // time to display the splash screen in ms
    
    
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splashscreen);
    
        Thread splashTread = new Thread() {
            @Override
            public void run() {
                try {
                    int waited = 0;
                    while (_active && (waited < _splashTime)) {
                        sleep(100);
                        if (_active) {
                            waited += 100;
                        }
                    }
                } catch (Exception e) {
    
                } finally {
    
                    startActivity(new Intent(SplashScreen.this,
                            MainActivity.class));
                    finish();
                }
            };
                 };
        splashTread.start();
    }
     }
    
  2. splashscreen.xml will be like this

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="600px" android:layout_height="1024px"
      android:background="#FF0000">
    </RelativeLayout> 
    
毁梦 2024-11-03 23:46:43

默认情况下,启动屏幕不会自动使您的应用程序看起来更专业。专业设计的启动屏幕有可能使您的应用程序看起来更专业,但如果您不知道如何编写启动屏幕,那么您的应用程序的其余部分实际上会多么专业。

拥有闪屏的唯一原因(借口)是因为您正在进行大量计算或正在等待 GPS/WiFi 启动,因为您的应用程序在启动之前依赖于它。如果没有这些计算的结果或访问 GPS/WiFi(等),您的应用程序就会死在水中,因此您觉得您需要一个启动屏幕,并且必须阻止任何其他正在运行的程序(包括背景)的屏幕视图)。

这样的启动画面应该看起来像您的全屏应用程序,给人一种它已经初始化的印象,然后在完成冗长的计算后,可以填写最终的细节(调整图像)。出现这种情况的机会或者这是设计该程序的唯一方式机会非常小。

最好允许用户(以及操作系统的其余部分)在等待时做其他事情,而不是将您的程序设计为依赖于需要一段时间的事情(当等待时间不确定时)。

您的手机上已经有一些图标表明 GPS/WiFi 正在启动。初始屏幕占用的时间或空间可能用于加载预先计算或实际进行计算。请参阅下面的第一个链接,了解您产生的问题以及必须考虑的事项。

如果您绝对必须等待这些计算或 GPS/WiFi,最好只是让应用程序启动并弹出一个窗口,提示有必要等待计算(文本“初始化”消息即可)。预计会等待 GPS/WiFi(如果尚未在其他程序中启用它们),因此无需宣布其等待时间。

请记住,当启动画面启动时,您的程序实际上已经在运行,您所做的只是延迟程序的使用并占用 CPU/GPU 来执行大多数人认为没有必要的操作。

我们最好真的想在每次启动您的程序时等待并看到您的启动屏幕,否则我们不会觉得它写得非常专业。使启动屏幕全屏和实际程序屏幕的副本(因此我们认为它已初始化,但实际上尚未初始化)可能会实现您的目标(使您的程序看起来更专业),但我不会对此打赌太多。

为什么不这样做:http://cyrilmottier.com/2012 /05/03/splash-screens-are-evil-dont-use-them/

如何操作:https://crypted.google.com/search?q=Android+splash+screen+source

所以有充分的理由不这样做,但如果你确定你的情况是这样的如果不属于这些示例,则上面给出了执行此操作的方法。确保它确实使您的申请看起来更专业,或者您已经否定了您这样做的唯一原因。

它就像一个 YouTube 频道,每个视频都以冗长的图形介绍(和结尾)开始,或者觉得有必要讲一个笑话或解释过去一周发生的事情(当它不是喜剧或生活方式频道时)。只是展示节目! (只需运行该程序)。

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).

眼泪淡了忧伤 2024-11-03 23:46:43

最重要的是,所有答案都非常好。但是会遇到内存泄漏的问题。
此问题在 Android 社​​区中通常称为“泄漏 Activity”。那到底是什么意思呢?

当配置发生更改(例如方向更改)时,Android 会销毁 Activity 并重新创建它。通常,垃圾收集器只会清除旧 Activity 实例分配的内存,这样就一切顺利了。

“泄漏 Activity” 是指垃圾收集器无法清除旧 Activity 实例分配的内存的情况,因为它被已存在的对象(强)引用活动实例。每个 Android 应用程序都有为其分配的特定内存量。当垃圾收集器无法释放未使用的内存时,应用的性能将逐渐下降,最终崩溃并出现 OutOfMemory 错误。

如何判断应用是否存在内存泄漏?最快的方法是在 Android Studio 中打开“内存”选项卡,并在更改方向时注意分配的内存。
如果分配的内存不断增加并且从不减少,那么就会发生内存泄漏。

1.用户改变方向时内存泄漏。
输入图像描述这里

首先,您需要在布局资源 splashscreen.xml 文件中定义启动屏幕

启动屏幕活动的示例代码。

public class Splash extends Activity {
 // 1. Create a static nested class that extends Runnable to start the main Activity
    private static class StartMainActivityRunnable implements Runnable {
        // 2. Make sure we keep the source Activity as a WeakReference (more on that later)
        private WeakReference mActivity;

        private StartMainActivityRunnable(Activity activity) {
         mActivity = new WeakReference(activity);
        }

        @Override
        public void run() {
         // 3. Check that the reference is valid and execute the code
            if (mActivity.get() != null) {
             Activity activity = mActivity.get();
             Intent mainIntent = new Intent(activity, MainActivity.class);
             activity.startActivity(mainIntent);
             activity.finish();
            }
        }
    }

    /** Duration of wait **/
    private final int SPLASH_DISPLAY_LENGTH = 1000;

    // 4. Declare the Handler as a member variable
    private Handler mHandler = new Handler();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(icicle);
        setContentView(R.layout.splashscreen);

        // 5. Pass a new instance of StartMainActivityRunnable with reference to 'this'.
        mHandler.postDelayed(new StartMainActivityRunnable(this), SPLASH_DISPLAY_LENGTH);
    }

    // 6. Override onDestroy()
    @Override
    public void onDestroy() {
     // 7. Remove any delayed Runnable(s) and prevent them from executing.
     mHandler.removeCallbacksAndMessages(null);

     // 8. Eagerly clear mHandler allocated memory
     mHandler = null;
    }
}

有关更多信息,请浏览此 链接

Above all answers are really very good. But there are encounter problem of memory leakage.
This issue is often known in the Android community as "Leaking an Activity". Now what exactly does that mean?

When configuration change occurs, such as orientation change, Android destroys the Activity and recreates it. Normally, the Garbage Collector will just clear the allocated memory of the old Activity instance and we're all good.

"Leaking an Activity" refers to the situation where the Garbage Collector cannot clear the allocated memory of the old Activity instance since it's being (strong) referenced from an object that out lived the Activity instance. Every Android app has a specific amount of memory allocated for it. When Garbage Collector cannot free up unused memory, the app's performance will decrease gradually and eventually crash with OutOfMemory error.

How to determine whether the app leaks memory or not? The fastest way is to open the Memory tab in Android Studio and pay attention to allocated memory as you change the orientation.
If the allocated memory keeps on increasing and never decreases then you have a memory leak.

1.Memory leak when user change the orientation.
enter image description here

First you need to define the splash screen in your layout resource splashscreen.xml file

Sample Code for splash screen activity.

public class Splash extends Activity {
 // 1. Create a static nested class that extends Runnable to start the main Activity
    private static class StartMainActivityRunnable implements Runnable {
        // 2. Make sure we keep the source Activity as a WeakReference (more on that later)
        private WeakReference mActivity;

        private StartMainActivityRunnable(Activity activity) {
         mActivity = new WeakReference(activity);
        }

        @Override
        public void run() {
         // 3. Check that the reference is valid and execute the code
            if (mActivity.get() != null) {
             Activity activity = mActivity.get();
             Intent mainIntent = new Intent(activity, MainActivity.class);
             activity.startActivity(mainIntent);
             activity.finish();
            }
        }
    }

    /** Duration of wait **/
    private final int SPLASH_DISPLAY_LENGTH = 1000;

    // 4. Declare the Handler as a member variable
    private Handler mHandler = new Handler();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(icicle);
        setContentView(R.layout.splashscreen);

        // 5. Pass a new instance of StartMainActivityRunnable with reference to 'this'.
        mHandler.postDelayed(new StartMainActivityRunnable(this), SPLASH_DISPLAY_LENGTH);
    }

    // 6. Override onDestroy()
    @Override
    public void onDestroy() {
     // 7. Remove any delayed Runnable(s) and prevent them from executing.
     mHandler.removeCallbacksAndMessages(null);

     // 8. Eagerly clear mHandler allocated memory
     mHandler = null;
    }
}

For more information please go through this link

吾性傲以野 2024-11-03 23:46:43

这是完整的代码

SplashActivity.java

public class SplashActivity extends AppCompatActivity {

private final int SPLASH_DISPLAY_DURATION = 1000;

@Override
public void onCreate(Bundle bundle) {
    super.onCreate(bundle);


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

            Intent mainIntent = new Intent(SplashActivity.this,MainActivity.class);
            SplashActivity.this.startActivity(mainIntent);
            SplashActivity.this.finish();
        }
    }, SPLASH_DISPLAY_DURATION);
}}

在drawables中创建这个bg_splash.xml

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

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

<item>
    <bitmap
        android:gravity="center"
        android:src="@drawable/ic_in_app_logo_big"/>
</item></layer-list>

styles.xml创建一个自定义主题

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

,最后在 >AndroidManifest.xml 指定您的 Activity Cheers 的主题

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

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

This is the full code here

SplashActivity.java

public class SplashActivity extends AppCompatActivity {

private final int SPLASH_DISPLAY_DURATION = 1000;

@Override
public void onCreate(Bundle bundle) {
    super.onCreate(bundle);


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

            Intent mainIntent = new Intent(SplashActivity.this,MainActivity.class);
            SplashActivity.this.startActivity(mainIntent);
            SplashActivity.this.finish();
        }
    }, SPLASH_DISPLAY_DURATION);
}}

In drawables create this bg_splash.xml

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

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

<item>
    <bitmap
        android:gravity="center"
        android:src="@drawable/ic_in_app_logo_big"/>
</item></layer-list>

In styles.xml create a custom theme

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

and finally in AndroidManifest.xml specify the theme to your activity

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

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

Cheers.

娇俏 2024-11-03 23:46:43

启动画面不应从布局文件加载,加载时可能仍存在一些延迟。

最好的方法是为您的 SplashScreenActivity 创建一个主题,并将 android:windowBackground 设置为可绘制资源。

https://www.bignerdranch.com/blog/splash-screens- the-right-way/

简而言之:

在清单中声明您的 SplashScreenActivity:

<activity
        android:name=".activities.SplashScreenActivity"
        android:theme="@style/SplashTheme"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

在您的 SplashScreenActivity.java 中:

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

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

}

接下来为主题的背景窗口创建资源:

<style name="SplashTheme" parent="Theme.Bumpfie.Base">
    <item name="android:windowBackground">@drawable/splash</item>
</style>

可绘制文件splash.xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@android:color/white"/>
    <item>
        <bitmap
            android:gravity="center"
            android:src="@drawable/app_logo"/>
    </item>
</layer-list>

Splash screens should not be loaded from a layout file, there might still be some lag when loading it.

The best way is to create a Theme just for your SplashScreenActivity and set the android:windowBackground to a drawable ressource.

https://www.bignerdranch.com/blog/splash-screens-the-right-way/

In a nutshell:

Declare your SplashScreenActivity in the manifest:

<activity
        android:name=".activities.SplashScreenActivity"
        android:theme="@style/SplashTheme"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

In your SplashScreenActivity.java:

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

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

}

Next create the ressource for the background window of your theme:

<style name="SplashTheme" parent="Theme.Bumpfie.Base">
    <item name="android:windowBackground">@drawable/splash</item>
</style>

Drawable file splash.xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@android:color/white"/>
    <item>
        <bitmap
            android:gravity="center"
            android:src="@drawable/app_logo"/>
    </item>
</layer-list>
夏末 2024-11-03 23:46:43

在 Android Marshmallow 之后,我想到的闪屏的其他高效使用是在应用程序的闪屏中请求必要的 Android 权限

似乎大多数应用程序都以这种方式处理权限请求。

  • 对话框会造成糟糕的 UIX,它们会破坏主流并让您决定运行时,而事实是大多数用户甚至可能不关心您的应用程序是否要在 SD 卡上写入内容。他们中的一些人甚至可能不明白我们想要传达的内容,直到我们将其翻译成简单的英语。

  • 一次请求权限可以减少每次操作前的“if else”数量,并使您的代码看起来更整洁。

这是一个示例,说明如何在运行 Android OS 23+ 的设备的启动活动中请求权限。

如果所有权限均已授予或已授予或应用程序正在 Pre Marshmallow 上运行,那么只需半秒的延迟即可显示主要内容,以便用户可以欣赏我们在阅读此问题并尽力而为时所付出的努力。

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);
    }


}

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);
    }


}
像你 2024-11-03 23:46:43
public class MainActivity extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Thread t=new Thread()
    {

        public void run()
        {   

            try {

                sleep(2000);
                finish();
                Intent cv=new Intent(MainActivity.this,HomeScreen.class/*otherclass*/);
                startActivity(cv);
            } 

            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    t.start();
}
public class MainActivity extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Thread t=new Thread()
    {

        public void run()
        {   

            try {

                sleep(2000);
                finish();
                Intent cv=new Intent(MainActivity.this,HomeScreen.class/*otherclass*/);
                startActivity(cv);
            } 

            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    t.start();
}
梦忆晨望 2024-11-03 23:46:43

创建一个 Activity,让我们将 Activity 命名为“A”,然后创建一个名为 myscreen.xml 的 xml 文件,在其中设置启动屏幕图像作为背景,然后使用倒计时器从一个 Activity 导航到另一个 Activity。要了解如何使用倒计时计时器,请参阅我在这个问题中的答案 Android 中的 TimerTask?

Create a Activity, let us Activity named 'A', then create a xml file called myscreen.xml, in that set a the splash screen image as background, and then use count down timer to navigate from one Activtity to another. To know how to use Count Down timer see my answer in this question TimerTask in Android?

思念满溢 2024-11-03 23:46:43

启动画面示例:

public class MainActivity extends Activity {
    private ImageView splashImageView;
    boolean splashloading = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        splashImageView = new ImageView(this);
        splashImageView.setScaleType(ScaleType.FIT_XY);
        splashImageView.setImageResource(R.drawable.ic_launcher);
        setContentView(splashImageView);
        splashloading = true;
        Handler h = new Handler();
        h.postDelayed(new Runnable() {
            public void run() {
                splashloading = false;
                setContentView(R.layout.activity_main);
            }

        }, 3000);

    }

}

Splash screen example :

public class MainActivity extends Activity {
    private ImageView splashImageView;
    boolean splashloading = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        splashImageView = new ImageView(this);
        splashImageView.setScaleType(ScaleType.FIT_XY);
        splashImageView.setImageResource(R.drawable.ic_launcher);
        setContentView(splashImageView);
        splashloading = true;
        Handler h = new Handler();
        h.postDelayed(new Runnable() {
            public void run() {
                splashloading = false;
                setContentView(R.layout.activity_main);
            }

        }, 3000);

    }

}
深爱成瘾 2024-11-03 23:46:43

启动画面是 Android 中一个不太可用的对象:它无法尽快加载,以隐藏主 Activity 启动的延迟。使用它有两个原因:广告和网络运营。

作为对话框实现可以毫不延迟地从启动屏幕跳转到 Activity 的主 UI。

public class SplashDialog extends Dialog {
    ImageView splashscreen;
    SplashLoader loader;
    int splashTime = 4000;

    public SplashDialog(Context context, int theme) {
        super(context, theme);
    }

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

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                cancel();
            }
        }, splashTime);

    }
}

布局:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/white">

    <ImageView
        android:id="@+id/splashscreen"
        android:layout_width="190dp"
        android:layout_height="190dp"
        android:background="@drawable/whistle"
        android:layout_centerInParent="true" />

</RelativeLayout>

并开始:

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

        if (getIntent().getCategories() != null &&  getIntent().getCategories().contains("android.intent.category.LAUNCHER")) {
            showSplashScreen();
        }
    }

    protected Dialog splashDialog;
    protected void showSplashScreen() {
        splashDialog = new SplashDialog(this, R.style.SplashScreen);
        splashDialog.show();
    }

    ...
}

Splash screen is a little unusable object in Android: it can not be loaded as soon as possible for hiding the delay of main activity starting. There are two reasons to use it: advertising and network operations.

Implementation as dialog makes jump without delay from splash screen to main UI of activity.

public class SplashDialog extends Dialog {
    ImageView splashscreen;
    SplashLoader loader;
    int splashTime = 4000;

    public SplashDialog(Context context, int theme) {
        super(context, theme);
    }

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

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                cancel();
            }
        }, splashTime);

    }
}

Layout:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/white">

    <ImageView
        android:id="@+id/splashscreen"
        android:layout_width="190dp"
        android:layout_height="190dp"
        android:background="@drawable/whistle"
        android:layout_centerInParent="true" />

</RelativeLayout>

And start:

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

        if (getIntent().getCategories() != null &&  getIntent().getCategories().contains("android.intent.category.LAUNCHER")) {
            showSplashScreen();
        }
    }

    protected Dialog splashDialog;
    protected void showSplashScreen() {
        splashDialog = new SplashDialog(this, R.style.SplashScreen);
        splashDialog.show();
    }

    ...
}
时光暖心i 2024-11-03 23:46:43

另一种方法是使用 CountDownTimer 来实现

@Override
public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.splashscreen);

 new CountDownTimer(5000, 1000) { //5 seconds
      public void onTick(long millisUntilFinished) {
          mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
      }

     public void onFinish() {
          startActivity(new Intent(SplashActivity.this, MainActivity.class));
          finish();
     }

  }.start();
}

Another approach is achieved by using CountDownTimer

@Override
public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.splashscreen);

 new CountDownTimer(5000, 1000) { //5 seconds
      public void onTick(long millisUntilFinished) {
          mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
      }

     public void onFinish() {
          startActivity(new Intent(SplashActivity.this, MainActivity.class));
          finish();
     }

  }.start();
}
萌辣 2024-11-03 23:46:43

有时,用户打开 SplashActivity 并立即退出,但应用在 SPLASH_SCREEN_DISPLAY_LENGTH 后仍会转到 MainActivity

为了防止它:在 SplashActivity 中,您应该在移动到 MainActivity 之前检查 SplashActivity 是否完成

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);
        }                             
   }                                
}

希望这有帮助

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

牵你手 2024-11-03 23:46:43
     - Add in SplashActivity 

   public class SplashActivity extends Activity {

       private ProgressBar progressBar;
       int i=0;
       Context context;
       private GoogleApiClient googleApiClient;

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

           new Handler().postDelayed(new Runnable() {
               @Override
               public void run() {
                   startActivity(new Intent(Splash.this, LoginActivity.class));
                   finish();
               }
           }, 2000);

       }

   }

  - Add in activity_splash.xml

   <RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns:tools="http://schemas.android.com/tools"
       xmlns:custom="http://schemas.android.com/apk/res-auto"
       android:background="@color/colorAccent"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       tools:context=".Splash">

       <ImageView
           android:id="@+id/ivLogo"
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:src="@mipmap/icon_splash"
           android:layout_centerHorizontal="true"
           android:layout_centerVertical="true"/>


       <ProgressBar
           android:id="@+id/circle_progress"
           style="?android:attr/progressBarStyleHorizontal"
           android:layout_width="fill_parent"
           android:layout_height="wrap_content"
           android:layout_alignParentBottom="true"
           android:layout_marginBottom="5dp"
           android:max="100"
           android:progressTint="@color/green"
           android:visibility="visible" />

   </RelativeLayout>

  - Add in AndroidManifest.xml

    <activity android:name="ex.com.SplashActivity">
               <intent-filter>
                   <action android:name="android.intent.action.MAIN" />

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

   public class SplashActivity extends Activity {

       private ProgressBar progressBar;
       int i=0;
       Context context;
       private GoogleApiClient googleApiClient;

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

           new Handler().postDelayed(new Runnable() {
               @Override
               public void run() {
                   startActivity(new Intent(Splash.this, LoginActivity.class));
                   finish();
               }
           }, 2000);

       }

   }

  - Add in activity_splash.xml

   <RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns:tools="http://schemas.android.com/tools"
       xmlns:custom="http://schemas.android.com/apk/res-auto"
       android:background="@color/colorAccent"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       tools:context=".Splash">

       <ImageView
           android:id="@+id/ivLogo"
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:src="@mipmap/icon_splash"
           android:layout_centerHorizontal="true"
           android:layout_centerVertical="true"/>


       <ProgressBar
           android:id="@+id/circle_progress"
           style="?android:attr/progressBarStyleHorizontal"
           android:layout_width="fill_parent"
           android:layout_height="wrap_content"
           android:layout_alignParentBottom="true"
           android:layout_marginBottom="5dp"
           android:max="100"
           android:progressTint="@color/green"
           android:visibility="visible" />

   </RelativeLayout>

  - Add in AndroidManifest.xml

    <activity android:name="ex.com.SplashActivity">
               <intent-filter>
                   <action android:name="android.intent.action.MAIN" />

                   <category android:name="android.intent.category.LAUNCHER" />
               </intent-filter>
           </activity>
爱本泡沫多脆弱 2024-11-03 23:46:43

真的很容易& gr8 方法:

享受!

这里有足够的答案将有助于实施。这篇文章的目的是帮助其他人完成创建启动画面的第一步!

Really easy & gr8 approach :

Enjoy!

There are enough answers here that will help with the implementation. this post was meant to help others with the first step of creating the splash screen!

不奢求什么 2024-11-03 23:46:43

在 Kotlin 中编写以下代码:-

 Handler().postDelayed({
            val mainIntent = Intent(this@SplashActivity, LoginActivity::class.java)
            startActivity(mainIntent)
            finish()
        }, 500)

希望这对您有帮助。谢谢........

In Kotlin write this code:-

 Handler().postDelayed({
            val mainIntent = Intent(this@SplashActivity, LoginActivity::class.java)
            startActivity(mainIntent)
            finish()
        }, 500)

Hope this will help you.Thanks........

爱你不解释 2024-11-03 23:46:43

一个超级灵活的启动屏幕怎么样,它可以使用相同的代码并在 AndroidManifest.xml 中定义,这样代码就永远不需要更改。我通常开发代码库,不喜欢自定义代码,因为它很草率。

<activity
        android:name=".SplashActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <meta-data android:name="launch_class" android:value="com.mypackage.MyFirstActivity" />
        <meta-data android:name="duration" android:value="5000" />
</activity>

然后,SpashActivity 本身查找“launch_class”的元数据,然后生成 Intent 本身。元数据“持续时间”定义了启动屏幕保持运行的时间。

public class SplashActivity extends Activity {

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

    ComponentName componentName = new ComponentName(this, this.getClass());

    try {
        Bundle bundle = null;
        bundle = getPackageManager().getActivityInfo(componentName, PackageManager.GET_META_DATA).metaData;
        String launch_class = bundle.getString("launch_class");
        //default of 2 seconds, otherwise defined in manifest
        int duration = bundle.getInt("duration", 2000);

        if(launch_class != null) {
            try {
                final Class<?> c = Class.forName(launch_class);

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent(SplashActivity.this, c);
                        startActivity(intent);
                        finish();
                    }
                }, duration);

            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
  }
}

How about a super-flexible launch screen that can use the same code and is defined in the AndroidManifest.xml, so the code will never need to change. I generally develop libraries of code and do not like customizing code because it is sloppy.

<activity
        android:name=".SplashActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <meta-data android:name="launch_class" android:value="com.mypackage.MyFirstActivity" />
        <meta-data android:name="duration" android:value="5000" />
</activity>

Then the SpashActivity itself looks up the meta-data for "launch_class" to then make the Intent itself. The meta data "duration" defines how long the splash screen stays up.

public class SplashActivity extends Activity {

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

    ComponentName componentName = new ComponentName(this, this.getClass());

    try {
        Bundle bundle = null;
        bundle = getPackageManager().getActivityInfo(componentName, PackageManager.GET_META_DATA).metaData;
        String launch_class = bundle.getString("launch_class");
        //default of 2 seconds, otherwise defined in manifest
        int duration = bundle.getInt("duration", 2000);

        if(launch_class != null) {
            try {
                final Class<?> c = Class.forName(launch_class);

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent(SplashActivity.this, c);
                        startActivity(intent);
                        finish();
                    }
                }, duration);

            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
  }
}
与之呼应 2024-11-03 23:46:43

虽然有很好的答案,但我将展示谷歌推荐的方法:

1)首先为启动屏幕创建一个Theme
您有一个名为 splashscreenTheme 的主题,您的启动器主题将是:

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

注意:

android:windowBackground 已将您的闪屏图像设置为 no
需要在 UI 中再次执行此操作。

您还可以在这里使用颜色而不是可绘制的。

2)将主题设置为splashscreenActivity的manifest

   <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)如果您的图像不小,请确保您的launch_screen drawable不在drawable文件夹中。

这将导致更快的启动屏幕启动并将您从黑屏中拯救出来

它还可以避免额外的透支

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

情话已封尘 2024-11-03 23:46:43

这是我在启动屏幕上看到的最好的帖子:http://saulmm.github。 io/avoding-android-cold-starts

Saúl Molinero 提出了两种不同的启动屏幕选项:利用窗口背景以动画方式进入初始屏幕并显示占位符 UI(这是 Google 用于的流行选择)如今他们的大部分应用程序)。

每当我需要考虑冷启动时间并避免由于启动时间过长而导致用户流失时,我都会参考这篇文章。

希望这有帮助!

This is the best post I've seen on splash screens: http://saulmm.github.io/avoding-android-cold-starts

Saúl Molinero goes into two different options for splash screens: Taking advantage of the window background to animate into your initial screen and displaying placeholder UI (which is a popular choice that Google uses for most of their apps these days).

I refer to this post every time I need to consider cold start time and avoiding user dropoff due to long startup times.

Hope this helps!

八巷 2024-11-03 23:46:43

就我而言,我不想创建一个新的 Activity 只是为了显示图像 2 秒。当启动我的 MainAvtivity 时,图像使用 picasso 加载到支架中,我知道这需要大约 1 秒的时间来加载,所以我决定在我的 MainActivity OnCreate 中执行以下操作

splashImage = (ImageView) findViewById(R.id.spllll);

    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

    int secondsDelayed = 1;
    new Handler().postDelayed(new Runnable() {
        public void run() {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            splashImage.setVisibility(View.GONE);

        }
    }, secondsDelayed * 2000);

:启动应用程序,首先发生的事情是显示 ImageView,并通过将窗口标志设置为全屏来删除状态栏。然后我使用 Handler 运行 2 秒,2 秒后我清除全屏标志并将 ImageView 的可见性设置为 GONE。容易、简单、有效。

In my case I didn't want to create a new Activity only to show a image for 2 seconds. When starting my MainAvtivity, images gets loaded into holders using picasso, I know that this takes about 1 second to load so I decided to do the following inside my MainActivity OnCreate:

splashImage = (ImageView) findViewById(R.id.spllll);

    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

    int secondsDelayed = 1;
    new Handler().postDelayed(new Runnable() {
        public void run() {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            splashImage.setVisibility(View.GONE);

        }
    }, secondsDelayed * 2000);

When starting the application the first thing that happens is the ImageView gets displayed and the statusBar is removed by setting the window flags to full screen. Then I used a Handler to run for 2 seconds, after the 2 seconds I clear the full screen flags and set the visibility of the ImageView to GONE. Easy, simple, effective.

土豪我们做朋友吧 2024-11-03 23:46:43

在 Android 中它非常简单,我们只需使用处理程序概念来实现启动屏幕

在您的 SplashScreenActivity java 文件 中粘贴此代码。

在您的 SplashScreenActivity xml 文件 中放置使用 imageview 的任何图片。

public void LoadScreen() {
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {                 
                Intent i = new Intent(SplashScreenActivity.this, AgilanbuGameOptionsActivity.class);
                startActivity(i);
            }
        }, 2000);
    }

Its really simple in android we just use handler concept to implement the splash screen

In your SplashScreenActivity java file paste this code.

In your SplashScreenActivity xml file put any picture using imageview.

public void LoadScreen() {
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {                 
                Intent i = new Intent(SplashScreenActivity.this, AgilanbuGameOptionsActivity.class);
                startActivity(i);
            }
        }, 2000);
    }
猫腻 2024-11-03 23:46:43

您可以将其添加到 onCreate 方法中

new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    // going to next activity
                    Intent i=new Intent(SplashScreenActivity.this,MainActivity.class);
                    startActivity(i);
                    finish();
                }
            },time);

,并根据需要以毫秒为单位初始化时间值...

private  static int time=5000;

有关更多详细信息,请从此链接下载完整代码...

https://github.com/Mr-Perfectt/Splash-Screen

You can add this in your onCreate Method

new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    // going to next activity
                    Intent i=new Intent(SplashScreenActivity.this,MainActivity.class);
                    startActivity(i);
                    finish();
                }
            },time);

And initialize your time value in milliseconds as yo want...

private  static int time=5000;

for more detail download full code from this link...

https://github.com/Mr-Perfectt/Splash-Screen

看海 2024-11-03 23:46:43

这是一个简单的!

~Lunox

MainActivity.java

package com.example.splashscreen;

import androidx.appcompat.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);
    }
}

splashscreen.java

package com.example.splashscreen;

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

public class splashscreen extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splashscreen);

        //Splash Screen duration
        int secondsDelayed = 1;
        new Handler().postDelayed(new Runnable() {
            public void run() {
                startActivity(new Intent(splashscreen.this, MainActivity.class));
                finish();
            }
        }, secondsDelayed * 3000);
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

splashscreen.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/splashlogo"

    />

<强>splashlogo.png

splashlogo.png

GitHub

SplashScreen

Here is a simple one!

~Lunox

MainActivity.java

package com.example.splashscreen;

import androidx.appcompat.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);
    }
}

splashscreen.java

package com.example.splashscreen;

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

public class splashscreen extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splashscreen);

        //Splash Screen duration
        int secondsDelayed = 1;
        new Handler().postDelayed(new Runnable() {
            public void run() {
                startActivity(new Intent(splashscreen.this, MainActivity.class));
                finish();
            }
        }, secondsDelayed * 3000);
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

splashscreen.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/splashlogo"

    />

splashlogo.png

splashlogo.png

GitHub

SplashScreen

找回味觉 2024-11-03 23:46:43

一种方法是创建 FullScreenActivity/EmptyActivity(例如 SplashScreenActivity)并将其设置为打开应用程序时显示的第一个 Activity。将以下内容添加到 AndroidManifest.xml 中的 Activity,

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

然后您可以设置一个处理程序以在几秒钟后关闭此 Activity。

new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent i= new Intent(SplashScreenActivity.this,MainActivity.class);
                startActivity(i); //start new activity 
                finish();
            }
        }, 3000); //time in milliseconds

其次,如果您不想创建单独的活动,您可以在 MainActivity 上膨胀布局,并将布局可见性设置为GONE或者在几毫秒后将主布局扩展到现有的初始屏幕布局。

One way is by creating a FullScreenActivity/EmptyActivity (say SplashScreenActivity) and set it as the first Activity that shows up when you open your app. Add the following to your Activity in the AndroidManifest.xml

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

You can then set a handler to dismiss this activity after a few seconds.

new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent i= new Intent(SplashScreenActivity.this,MainActivity.class);
                startActivity(i); //start new activity 
                finish();
            }
        }, 3000); //time in milliseconds

Secondly, if you don't wish to create a separate activity, you can inflate a layout over your MainActivity and set the layout visibility to GONE or inflate the main layout over the existing splash screen layout after a few milliseconds.

凑诗 2024-11-03 23:46:43

简单的代码,它有效:) 简单的启动

int secondsDelayed = 1;
    new Handler().postDelayed(new Runnable() {
        public void run() {
            startActivity(new Intent(LoginSuccessFull.this, LoginActivity.class));
            finish();
        }
    }, secondsDelayed * 1500);

Simple Code, it works:) Simple splash

int secondsDelayed = 1;
    new Handler().postDelayed(new Runnable() {
        public void run() {
            startActivity(new Intent(LoginSuccessFull.this, LoginActivity.class));
            finish();
        }
    }, secondsDelayed * 1500);
爱要勇敢去追 2024-11-03 23:46:43
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();
  }
}
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();
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文