三秒倒计时

本文介绍了一个基于AppCompatActivity的LoginActivity类实现,该类通过TextView显示倒计时,并使用SharedPreferences存储用户状态。当用户状态为已登录时,将跳转至MainActivity。代码中还包含了Handler的消息处理机制和线程的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Activity页面

public class LoginActivity extends AppCompatActivity {

private TextView textView;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
private int i = 3;
@SuppressLint("HandlerLeak")
private Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {

        textView.setText(msg.what+"s");
        if(msg.what == 0){
            editor.putBoolean("c_t",true);
            editor.commit();
            Intent intent = new Intent(LoginActivity.this,MainActivity.class);
            startActivity(intent);
            finish();
        }

    }
};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    textView = findViewById(R.id.tet);
    sharedPreferences = getSharedPreferences("user",MODE_PRIVATE);
    editor = sharedPreferences.edit();
    boolean c_t = sharedPreferences.getBoolean("c_t",false);
    if(c_t){
        Intent intent = new Intent(LoginActivity.this,MainActivity.class);
        startActivity(intent);
        finish();
    }else {
        new Thread() {
            @Override
            public void run() {
                super.run();
                while (i > 0) {
                    i--;
                    try {
                        sleep(1000);
                        handler.sendEmptyMessageDelayed(i, 1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

}
}

XML布局里面只有一个textview.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值