Android 如何 简单的添加 启动页 SplashScreen

1. 在 Android App 启动中, 为了体验优化,各大App 都是有 添加 启动页的, 比较土的 方法就是直接 弄个 loadingActivity, 充当启动页, 在启动初始化相关工作做完以后,再跳转. 就像下面这样.

themes.xml 代码

AndroidManifest.xml 代码

android:name=".xxxxx"

android:theme="@style/Fullscreen"

android:screenOrientation="landscape"

android:exported="true">

xxxxActivity.java 中 跳转

Intent intent=new Intent(xxxxx.this, xxxxx.class);

startActivity(intent);

2. 现在有 官方支持的方法 是通过 Android 12 加入的 SplashScreen.

这样体验会更好, 避免 Acitivity 跳转; 但是 Android 12 系统版本太新了,并不是主流,之前的版本怎么办呢? 现在有了:

AndroidX包也刚推出了一个叫SplashScreen的同名API。我们都知道AndroidX归属Jetpack,是独立于SDK版本以外的开发框架集合,很显然它就是用来兼容低版本的Splash Screen功能库。

Jetpack SplashScreen是向后兼容Android 12 Splash Screen功能的开发库。 其最早支持到Android 6(API 23),全球的Android设备中6及以上的版本占用率达到了9成以上,可以说完全够用了。

2.1 App的 build.gradle 中 需要引入 splashscreen 库支持

dependencies {

...

implementation 'androidx.core:core-splashscreen:1.0.0-beta01'

}

themes.xml 代码, 自定义 SplashScreen 主题, 一定要继承自 Theme.SplashScreen. 而 postSplashScreenTheme 是 指定目标Activity主题. 一定要指定, 根据你的 Activity 的父类确定,如果你的Activity 继承自 AppCompatActivity, 那么你的 主题也得是AppCompat系主题. 我这里 的 Activity 继承自 ComponentActivity, 所以可以是 非 AppCompat系主题.

同样, AndroidManifest.xml 代码

android:name=".xxxxx"

android:theme="@style/Theme.App.Starting"

android:screenOrientation="landscape"

android:exported="true">

xxxxActivity.java 中

public class MainActivity extends ComponentActivity {

private static boolean isReady = true;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

SplashScreen splash = SplashScreen.installSplashScreen(this);

setContentView(R.layout.activity_main);

splash.setKeepOnScreenCondition(() ->{

return isReady;

} );

// View contentView = findViewById(android.R.id.content);

// contentView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener(){

// @Override

// public boolean onPreDraw() {

// //Return true to proceed with the current drawing pass, or false to cancel.

// System.out.println("onPreDraw been called! ");

// return isReady;

// }

// });

这里, 可以通过 isReady 这个值 来控制是否继续显示 SplashScreen. 也就是是否跳转.

有两种方式 一种是 通过 ViewTreeObserver 的 OnPreDrawListener, 另一种是 SplashScreen 官方的 setKeepOnScreenCondition, 都能达到效果.

参考:

https://juejin.cn/post/6997217571208445965 Jetpack新成员SplashScreen:打造全新的App启动画面

https://www.jianshu.com/p/4f68d62c809b Android ViewTreeObserver使用总结

https://blog.csdn.net/guolin_blog/article/details/120275319 Android 12 SplashScreen API快速入门

https://github.com/ellisonchan/ComposeBird Demo 地址

Copyright © 2088 14年世界杯决赛_世界杯预选赛中国队出线形势 - pengxiaojing.com All Rights Reserved.
友情链接