实现启动app,首页倒计时跳转,也可点击按钮进行跳转

  • 1.在Drawable创建一个

text_background.xml




    
    



  • 2.设置布局

activity_main.xml




    





  • 3.设置java代码

MainActivity.java

package com.example.gl.countdown_text;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    /**
     * 跳转
     */
    private final static int COUNT = 1;
    private TextView countDown;
    private Timer timer;
    private Handler handler = new Handler() {
        int num = 5;

        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case COUNT:
                    countDown.setText(String.valueOf("跳转:" + num) + "s");
                    num--;
                    break;

                default:
                    break;
            }
        }

        ;
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化
        initView();
    }

    private void initView() {
        countDown = (TextView) findViewById(R.id.count_down);
        //点击按钮进行直接跳转
        countDown.setOnClickListener(this);


        // sehedule的第二个参数是第一次启动延时的时间,第三个是每隔多长时间执行一次
        timer = new Timer();
        final long end = System.currentTimeMillis() + 1000 * 5;
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(COUNT);
            }
        }, 0, 1000);

        //这里的schedule的第二个参数意义是到了这个时间尽快运行run里面的方法
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                startActivity(new Intent(MainActivity.this, MyActivity.class));
                finish();
                timer.cancel();
            }
        }, new Date(end));

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.count_down:
                startActivity(new Intent(MainActivity.this, MyActivity.class));
                //将timer进行取消
                finish();
                timer.cancel();
                break;
        }
    }
}

你可能感兴趣的:(实现启动app,首页倒计时跳转,也可点击按钮进行跳转)