android启动第一个界面时即闪屏的核心代码(两种方式)

时间:2021-05-21 16:46:54
闪屏,就是SplashScreen,也可以说是启动画面,就是启动的时候,闪(展示)一下,持续数秒后,自动关闭。

   第一种方式:

android的实现非常简单,使用Handler对象的postDelayed方法就可以实现。在这个方法里传递一个Runnable对象和一个延迟的时间。该方法实现了一个延迟执行的效果,延迟的时间由第2个参数指定,单位是毫秒。第一个参数是Runnable对象,里面包含了延迟后需要执行的操作。

具体的实现步骤为:

1.实现一个闪屏窗体,设置背景图片等。

2.实现主窗体,当闪屏结束后会启动该窗体。

2.在闪屏窗体里的onCreate方法重载里,处理一个延迟执行页面跳转的操作。方法如上面的代码所示。在这里跳转到程序的主窗体。


这里只给出核心代码,ui很简单就不给了

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

public class StarActivity extends Activity {

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

// 闪屏的核心代码
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(StarActivity.this,
MainActivity.class); // 从启动动画ui跳转到主ui
startActivity(intent);
overridePendingTransition(R.anim.in_from_right,
R.anim.out_to_left);
StarActivity.this.finish(); // 结束启动动画界面

}
}, 4000); // 启动动画持续3秒钟
}

}


第二种方式:

通过AlphaAnimation 动画,窗口的动画效果,淡入淡出,有些游戏的欢迎动画,logo的淡入淡出效果就使用AlphaAnimation。 

【基本语法】public AlphaAnimation (float fromAlpha, float toAlpha)

fromAlpha:开始时刻的透明度,取值范围0~1。
toAlpha:结束时刻的透明度,取值范围0~1。

public class SplashActivity extends Activity
{
private TextView tv_version;
private LinearLayout ll;
private ProgressDialog progressDialog;

private UpdateInfo info;
private String version;

private static final String TAG = "Security";

private Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
if(isNeedUpdate(version))
{
showUpdateDialog();
}
};
};

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

tv_version = (TextView) findViewById(R.id.tv_splash_version);
version = getVersion();
tv_version.setText("版本号 " + version);

ll = (LinearLayout) findViewById(R.id.ll_splash_main);
AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);
alphaAnimation.setDuration(2000);
ll.startAnimation(alphaAnimation);

progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("正在下载...");

new Thread()
{
public void run()
{
try
{
sleep(3000);
handler.sendEmptyMessage(0);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
};
}.start();

}


其实在启动界面会包括很多操作的,比如,获取应用的版本号,以及提醒是否更新,等等操作。这里也只给出简单的核心代码,一般也是很容易理解的。


上述代码只是简单的给出了一些操作,具体的实现没有给出,比如版本号,以及更新操作,下载操作等。如果没有上述的一些操作,只要注意如下代码即可。


 ll = (LinearLayout) findViewById(R.id.ll_splash_main);
AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);
alphaAnimation.setDuration(2000);
ll.startAnimation(alphaAnimation);