Android实现倒计时跳转Activity
16lz
2021-01-26
现在的APP大部分打开时的欢迎界面都有广告,倒计时结束进入主界面,今天就自己试试实现了一下,主要用到有:
Intent:意图,实现页面跳转
CountDownTimer:倒计时器,不言而喻
Handler:消息处理类,将跳转意图发送到消息队列,可以设置延迟
完整代码如下:
package com.example.sharedpreferences;import android.app.Activity;import android.content.Context;import android.content.Intent;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;import android.os.Bundle;import android.os.CountDownTimer;import android.os.Handler;import android.view.Window;import android.view.WindowManager;import android.widget.TextView;public class Welcome extends Activity {private static final String MY_DB_FirstCheck = "my_db";private TextView countdown;protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);this.requestWindowFeature(Window.FEATURE_NO_TITLE);this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);setContentView(R.layout.welcome_layout);countdown = (TextView) findViewById(R.id.TView_countdown);final SharedPreferences sharedpreferences = getSharedPreferences(MY_DB_FirstCheck, Context.MODE_PRIVATE);/** * Check if this is user's first visit; */final boolean hasVisited = sharedpreferences.getBoolean("hasVisited",false);/** * Default preference is 'false',if 'sharedpreferences' hasn't the * String 'hasVisited'. */countdowntimer = new MyCountdownTimer(3000, 1000);countdowntimer.start();handler.postDelayed(new Runnable() {@Overridepublic void run() {if (!hasVisited) {/** * Show Login Activity. */Intent intent = new Intent();intent.setClass(Welcome.this, Login.class);startActivity(intent);/** * Commit change: change state to 'true'. */Editor edit = sharedpreferences.edit();edit.putBoolean("hasVisited", true);edit.commit();} else {Intent intent = new Intent();intent.setClass(Welcome.this, MainActivity.class);startActivity(intent);}finish();}}, 3000);}private Handler handler = new Handler();private MyCountdownTimer countdowntimer;/** * Rewrite 'CountDownTimer' method. * * @param millisInFuture * 倒计时总数,单位为毫秒。 * @param countDownInterval * 每隔多久调用onTick一次 * @author DaiZhenWei * */protected class MyCountdownTimer extends CountDownTimer {public MyCountdownTimer(long millisInFuture, long countDownInterval) {super(millisInFuture, countDownInterval);}@Overridepublic void onTick(long millisUntilFinished) {countdown.setText("Close(" + millisUntilFinished / 1000 + ")");}@Overridepublic void onFinish() {countdown.setText("Turning");}}}
注意:finish()必须写在Runnable()中,写在方法外围会造成欢迎界面闪退,之后直接进入主界面
今天就写到这里,明天准备把倒计时那里加上点击事件,实现跳过等待时间的过程,暂时还没有想法,明天继续!
更多相关文章
- [Android(安卓)性能优化系列]布局篇之减少你的界面层级
- android v13 的新特性
- Android(安卓)消息推送通知指南
- android 局部界面动态切换
- Android(安卓)判断当前的界面是否是桌面的方法
- 我想邀请你和我一起写Android(福利回赠)
- android系统学习笔记八
- 【Android】Activity_习题
- 安卓视频通讯系统(SDK)