简介
- 我们常见的App启动时一般会先进入一个展示公司Logo的页面或一个广告页面,这个页面一般会延时几秒,之后进入主页面,这次我们实现的就是这个延时启动的几种方法
- 当然在这之前先将进入主页面的逻辑写出,进入主页面并finish当前页面
private void enterMainActivity() {
startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
finish();
}
private void initView() {
iv_welcome = (ImageView) findViewById(R.id.iv_welcome);
}
1. 动画延时进入
- 这里既可以用View动画也可以用属性动画,原理就是给动画添加动画结束监听,动画结束的同时进入主页面
1.1 View动画
private void initAlphaAnimator() {
AlphaAnimation animation = new AlphaAnimation(0.2f, 1.0f);
animation.setDuration(2000);
iv_welcome.setAnimation(animation);
animation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
enterMainActivity();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
}
1.2 属性动画
private void initAnimator() {
ObjectAnimator animator = ObjectAnimator.ofFloat(iv_welcome, "alpha", 0.2f, 1.0f);
animator.setDuration(2000);
animator.start();
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
enterMainActivity();
}
});
}
2. Timer定时器
private void initTimer() {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
enterMainActivity();
}
};
timer.schedule(task, 2000);
}
3. Handler + Message消息发送
- 延时发送Message,Handler在延时后接到Message立即执行handleMessage中的方法进入主页面
private void initHandler() {
handler.sendMessageDelayed(new Message(), 2000);
}
public Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
enterMainActivity();
}
};
4. 使用Handler中post方法实现延时
private void initHandlerPost() {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
enterMainActivity();
}
}, 2000);
}
5. 异步实现延时
private class WelcomeAsyncTask extends AsyncTask {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
enterMainActivity();
}
@Override
protected Object doInBackground(Object[] objects) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
}
private void initAsyncTask() {
WelcomeAsyncTask task = new WelcomeAsyncTask();
task.execute();
}