一、APP的启动方式:
一般来说,APP的启动方式主要分为两种:冷启动和热启动。
- 冷启动:启动应用时,后台没有该应用的进程,系统会重新创建一个新的进程分配给该应用,即冷启动;
- 热启动:启动应用时,后台已有该应用的进程(例如:点击Back键或Home键退出,此时应用的进程依然在后台存活),这时会在已有的进程中启动该应用,即热启动;
特点:
- 冷启动:由于冷启动需要系统重新创建一个新的进程,所以会先创建和初始化Application,然后再创建和初始化StartActivity(启动页Activity)并测量绘制其界面。从点击启动图标到启动完成(以看到界面的第一帧为准)应用的启动流程如下:
Application构造方法->attachBaseContext()->onCreate()->StartActivity构造方法->onCreate()->onStart()->onResume()->测量、绘制布局并展示;
- 热启动:由于后台已存在该应用的进程无需重新创建,且一个应用的进程从创建到销毁Application只会被初始化一次。所以热启动只会执行StartActivity的创建和初始化;
二、启动APP时白屏或黑屏:
现象:许多做Android的小伙伴可能都遇到过,当启动APP时, 会有一个白屏或黑屏一闪而过,然后才展示启动页的现象。这种诡异的现象又是如何产生的呢?
从上述APP的启动方式 的介绍中,我们可以知道只有在StartActivity的onResume()执行完成后才开始布局的测量和绘制。而在应用程序进程创建并初始化成功之前,系统会显示一个临时窗口Starting Window(也称作:Preview Window,它的WindowType是TYPE_APPLICATION_STARTING;在初始化完成之前展示,是为了尽快告知用户,系统已经知道他要打开该应用,并且已经对此做出了响应。待初始化完成后,系统会显示用户UI并移除该窗口),我们看到的黑屏或白屏就是不同Theme时对应的Window的背景。
启动白屏的示例:
- 设置启动页Style:
<style name="AppTheme.Launcher" parent="Theme.AppCompat.Light.NoActionBar">
<item name="windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
</style>
- 在AndroidManifest.xml中配置如下:
<activity
android:name=".activity.StartActivity"
android:theme="@style/AppTheme.Launcher">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
3.StartActivity的代码如下:
public class StartActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
try {
Thread.sleep(1000); //线程休眠1s,使出现白屏时的效果更加明显
} catch (InterruptedException e) {
e.printStackTrace();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
//展示2s后前往主页
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(StartActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}, 2000);
}
}
public class StartActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
try {
Thread.sleep(1000); //线程休眠1s,使出现白屏时的效果更加明显
} catch (InterruptedException e) {
e.printStackTrace();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
//展示2s后前往主页
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(StartActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}, 2000);
}
}
- 布局文件 activity_start.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/layer_launcher"
tools:context="com.gcj.myapplication.activity.StartActivity">
</FrameLayout>
效果如下:
解决方案:
- 禁用Preview Window(不推荐):
既然APP启动时的黑白屏是由Preview引起的,那系统有没有提供禁用的方法呢? 答案是肯定的。修改上述style 如下:
<style name="AppTheme.Launcher" parent="Theme.AppCompat.Light.NoActionBar">
<!--禁用Preview-->
<item name="android:windowDisablePreview">true</item>
<item name="windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
</style>
然而,黑白屏的问题是解决了,但点击应用图标后会有一段时间没有响应。用户体验不好,违背了优化的初衷,不推荐使用。
- 使用透明主题(个人不太推荐):
<style name="AppTheme.Launcher" parent="Theme.AppCompat.Light.NoActionBar">
<!--设置Window透明-->
<item name="android:windowIsTranslucent">true</item>
<item name="windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
</style>
特点:应用启动慢,刷新同步,界面会一次性刷新出来。由于背景透明,初始化的过程中,用户看到的是桌面,给人一种点击之后稍等一会才一次性刷新出来的感觉。
注:话说微信启动时使用的就是类似这样的效果,但微信做了一定的优化处理,只在 冷启动 时才显示启动页,具体如何实现稍后会做详细介绍;
- 修改windowBackground属性(推荐):
<style name="AppTheme.Launcher" parent="Theme.AppCompat.Light.NoActionBar">
<!-- 通过windowBackground可以设置背景色、背景图片、能解析出图片的XML文件等-->
<item name="android:windowBackground">@drawable/layer_launcher</item>
<item name="windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
</style>
自定义layer-list: layer_launcher.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/launch_logo" />
</item>
</layer-list>
特点:应用启动快,非同步刷新,界面会先显示背景图,然后再刷新其他控件,个人比较推荐。
注:此时可以将StartActivity中 setContentView(R.layout.activity_start); 注释掉;
三、从启动页到登录页的完美过渡:
通过上述方案,虽然解决了启动时黑屏、白屏的问题,但总感觉界面跳转时,过渡不够自然。之前一偶然机会实现了一个从启动页至登录页的过渡动画,动画比较简单,效果还算可以。江湖规矩,先呈上效果图:
附代码:
- 将AndroidManifest.xml中StartActivity的Theme配置为上述解决方案的第三种,StartActivity.java的代码如下:
package com.gcj.myapplication.activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
/**
* Created by gcj on 2017/11/28
*/
public class StartActivity extends AppCompatActivity {
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 注意:此处将setContentView()方法注释掉
// setContentView(R.layout.activity_start);
handler.postDelayed(new Runnable() {
@Override
public void run() {
gotoLogin();
}
}, 2000);
}
/**
* 前往注册、登录主页
*/
private void gotoLogin() {
Intent intent = new Intent(StartActivity.this, LoginMainActivity.class);
startActivity(intent);
finish();
//取消界面跳转时的动画,使启动页的logo图片与注册、登录主页的logo图片完美衔接
overridePendingTransition(0, 0);
}
/**
* 屏蔽物理返回键
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
protected void onDestroy() {
if (handler != null) {
//If token is null, all callbacks and messages will be removed.
handler.removeCallbacksAndMessages(null);
}
super.onDestroy();
}
}
package com.gcj.myapplication.activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
/**
* Created by gcj on 2017/11/28
*/
public class StartActivity extends AppCompatActivity {
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 注意:此处将setContentView()方法注释掉
// setContentView(R.layout.activity_start);
handler.postDelayed(new Runnable() {
@Override
public void run() {
gotoLogin();
}
}, 2000);
}
/**
* 前往注册、登录主页
*/
private void gotoLogin() {
Intent intent = new Intent(StartActivity.this, LoginMainActivity.class);
startActivity(intent);
finish();
//取消界面跳转时的动画,使启动页的logo图片与注册、登录主页的logo图片完美衔接
overridePendingTransition(0, 0);
}
/**
* 屏蔽物理返回键
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
protected void onDestroy() {
if (handler != null) {
//If token is null, all callbacks and messages will be removed.
handler.removeCallbacksAndMessages(null);
}
super.onDestroy();
}
}
- LoginMainActivity.java
package com.gcj.myapplication.activity;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.gcj.myapplication.R;
/**
* Created by gcj on 2017/11/28
*/
public class LoginMainActivity extends AppCompatActivity {
private long exitTime;
private TextView tvRegister;
private TextView tvLogin;
private ImageView ivLogo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_login);
initViews();
initAnims();
}
/**
* 初始化View控件
*/
private void initViews() {
tvLogin = (TextView) findViewById(R.id.tv_login);
tvRegister = (TextView) findViewById(R.id.tv_register);
ivLogo = (ImageView) findViewById(R.id.iv_logo);
}
/**
* 初始化logo图片以及底部注册、登录的按钮动画
*/
private void initAnims() {
//初始化底部注册、登录的按钮动画
//以控件自身所在的位置为原点,从下方距离原点200像素的位置移动到原点
ObjectAnimator tranLogin = ObjectAnimator.ofFloat(tvLogin, "translationY", 200, 0);
ObjectAnimator tranRegister = ObjectAnimator.ofFloat(tvRegister, "translationY", 200, 0);
//将注册、登录的控件alpha属性从0变到1
ObjectAnimator alphaLogin = ObjectAnimator.ofFloat(tvLogin, "alpha", 0, 1);
ObjectAnimator alphaRegister = ObjectAnimator.ofFloat(tvRegister, "alpha", 0, 1);
final AnimatorSet bottomAnim = new AnimatorSet();
bottomAnim.setDuration(1000);
//同时执行控件平移和alpha渐变动画
bottomAnim.play(tranLogin).with(tranRegister).with(alphaLogin).with(alphaRegister);
//获取屏幕高度
WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics metrics = new DisplayMetrics();
manager.getDefaultDisplay().getMetrics(metrics);
int screenHeight = metrics.heightPixels;
//通过测量,获取ivLogo的高度
int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
ivLogo.measure(w, h);
int logoHeight = ivLogo.getMeasuredHeight();
//初始化ivLogo的移动和缩放动画
float transY = (screenHeight - logoHeight) * 0.28f;
//ivLogo向上移动 transY 的距离
ObjectAnimator tranLogo = ObjectAnimator.ofFloat(ivLogo, "translationY", 0, -transY);
//ivLogo在X轴和Y轴上都缩放0.75倍
ObjectAnimator scaleXLogo = ObjectAnimator.ofFloat(ivLogo, "scaleX", 1f, 0.75f);
ObjectAnimator scaleYLogo = ObjectAnimator.ofFloat(ivLogo, "scaleY", 1f, 0.75f);
AnimatorSet logoAnim = new AnimatorSet();
logoAnim.setDuration(1000);
logoAnim.play(tranLogo).with(scaleXLogo).with(scaleYLogo);
logoAnim.start();
logoAnim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
//待ivLogo的动画结束后,开始播放底部注册、登录按钮的动画
bottomAnim.start();
}
});
}
/**
* 重写返回键,实现双击退出效果
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (System.currentTimeMillis() - exitTime > 2000) {
Toast.makeText(LoginMainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
LoginMainActivity.this.finish();
}
return true;
}
return super.onKeyDown(keyCode, event);
}
}
package com.gcj.myapplication.activity;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.gcj.myapplication.R;
/**
* Created by gcj on 2017/11/28
*/
public class LoginMainActivity extends AppCompatActivity {
private long exitTime;
private TextView tvRegister;
private TextView tvLogin;
private ImageView ivLogo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_login);
initViews();
initAnims();
}
/**
* 初始化View控件
*/
private void initViews() {
tvLogin = (TextView) findViewById(R.id.tv_login);
tvRegister = (TextView) findViewById(R.id.tv_register);
ivLogo = (ImageView) findViewById(R.id.iv_logo);
}
/**
* 初始化logo图片以及底部注册、登录的按钮动画
*/
private void initAnims() {
//初始化底部注册、登录的按钮动画
//以控件自身所在的位置为原点,从下方距离原点200像素的位置移动到原点
ObjectAnimator tranLogin = ObjectAnimator.ofFloat(tvLogin, "translationY", 200, 0);
ObjectAnimator tranRegister = ObjectAnimator.ofFloat(tvRegister, "translationY", 200, 0);
//将注册、登录的控件alpha属性从0变到1
ObjectAnimator alphaLogin = ObjectAnimator.ofFloat(tvLogin, "alpha", 0, 1);
ObjectAnimator alphaRegister = ObjectAnimator.ofFloat(tvRegister, "alpha", 0, 1);
final AnimatorSet bottomAnim = new AnimatorSet();
bottomAnim.setDuration(1000);
//同时执行控件平移和alpha渐变动画
bottomAnim.play(tranLogin).with(tranRegister).with(alphaLogin).with(alphaRegister);
//获取屏幕高度
WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics metrics = new DisplayMetrics();
manager.getDefaultDisplay().getMetrics(metrics);
int screenHeight = metrics.heightPixels;
//通过测量,获取ivLogo的高度
int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
ivLogo.measure(w, h);
int logoHeight = ivLogo.getMeasuredHeight();
//初始化ivLogo的移动和缩放动画
float transY = (screenHeight - logoHeight) * 0.28f;
//ivLogo向上移动 transY 的距离
ObjectAnimator tranLogo = ObjectAnimator.ofFloat(ivLogo, "translationY", 0, -transY);
//ivLogo在X轴和Y轴上都缩放0.75倍
ObjectAnimator scaleXLogo = ObjectAnimator.ofFloat(ivLogo, "scaleX", 1f, 0.75f);
ObjectAnimator scaleYLogo = ObjectAnimator.ofFloat(ivLogo, "scaleY", 1f, 0.75f);
AnimatorSet logoAnim = new AnimatorSet();
logoAnim.setDuration(1000);
logoAnim.play(tranLogo).with(scaleXLogo).with(scaleYLogo);
logoAnim.start();
logoAnim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
//待ivLogo的动画结束后,开始播放底部注册、登录按钮的动画
bottomAnim.start();
}
});
}
/**
* 重写返回键,实现双击退出效果
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (System.currentTimeMillis() - exitTime > 2000) {
Toast.makeText(LoginMainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
LoginMainActivity.this.finish();
}
return true;
}
return super.onKeyDown(keyCode, event);
}
}
- activity_main_login.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
tools:context="com.gcj.myapplication.activity.LoginMainActivity">
<TextView
android:id="@+id/tv_login"
android:layout_width="250dp"
android:layout_height="45dp"
android:layout_above="@+id/tv_register"
android:layout_centerHorizontal="true"
android:layout_marginBottom="23dp"
android:alpha="0"
android:background="@drawable/shape_login"
android:gravity="center"
android:text="登录"
android:textColor="@android:color/white"
android:textSize="15sp" />
<TextView
android:id="@+id/tv_register"
android:layout_width="250dp"
android:layout_height="45dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="102dp"
android:alpha="0"
android:background="@drawable/shape_login"
android:gravity="center"
android:text="新用户注册"
android:textColor="@android:color/white"
android:textSize="15sp" />
<ImageView
android:id="@+id/iv_logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="@drawable/launch_logo" />
</RelativeLayout>
四、实现只在冷启动时显示启动页,类似微信效果:
其实实现很简单,只需在启动页跳转到的主Activity(如上述:LoginMainActivity)中重写的返回键如下:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//实现只在冷启动时显示启动页,即点击返回键与点击HOME键退出效果一致
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
return true;
}
return super.onKeyDown(keyCode, event); }
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//实现只在冷启动时显示启动页,即点击返回键与点击HOME键退出效果一致
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
return true;
}
return super.onKeyDown(keyCode, event);
}