欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Handler倒计时

程序员文章站 2022-07-14 17:05:24
...
public class MainActivity extends BaseActivity {

    private TextView tiao;
    private SharedPreferences sp;
    private int time=5;
    @Override
    public int bindLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        tiao = findViewById(R.id.tiao);
        sp = getSharedPreferences("dao",Context.MODE_PRIVATE);
    }

    @Override
    protected void initData() {
        if (sp.getBoolean("登录",false)){
            startActivity(new Intent(MainActivity.this,ShowActivity.class));
            handler.removeCallbacksAndMessages(null);
            finish();
            return;
        }
        handler.sendEmptyMessageDelayed(0,1000);
    }

    @Override
    protected void bindEvent() {

        tiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences.Editor editor=sp.edit();
                editor.putBoolean("登录",true);
                editor.commit();
                startActivity(new Intent(MainActivity.this,ShowActivity.class));
                handler.removeCallbacksAndMessages(null);
                finish();
                return ;
            }
        });
    }

    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    if (time>0){
                        time--;
                        tiao.setText("跳转:"+time+"S");
                        handler.sendEmptyMessageDelayed(0,1000);
                    }else{
                        SharedPreferences.Editor editor=sp.edit();
                        editor.putBoolean("登录",true);
                        editor.commit();
                        startActivity(new Intent(MainActivity.this,ShowActivity.class));
                        handler.removeCallbacksAndMessages(null);
                        finish();
                    }
                    break;
            }

        }
    };
}
相关标签: 倒计时