Handler倒计时跳转
程序员文章站
2022-07-14 17:10:30
...
在布局里设置TextView控件
具体实现步骤
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import jiaoyibo.bawei.com.yuekao1.base.BaseActivity;
public class MainActivity extends BaseActivity {
private TextView time;
//设置时长
private int i =5;
private SharedPreferences sp;
private Handler handler = new Handler(){
//handler延迟发送信息并将秒数赋值给TextView
@Override
public void handleMessage(Message msg) {
if(msg.what==0){
i--;
if(i==0){
//获取值
sp.edit().putBoolean("isfirst",false).commit();
Intent intent = new Intent(MainActivity.this, ShowActivity.class);
startActivity(intent);
finish();
}
time.setText(i+"S");
//再次发送信息
handler.sendEmptyMessageDelayed(0,1000);
}
}
};
@Override
protected int getLayoutId() {
return R.layout.activity_main;
}
@Override
protected void initView() {
//找控件
time = findViewById(R.id.time);
}
@Override
protected void initData() {
//得到SharedPreferences通过键值对找到里边的boolean
sp = getSharedPreferences("config", MODE_PRIVATE);
//创建并传值
boolean isfirst = sp.getBoolean("isfirst", true);
//如果为true就证明进入过该页面,直接跳转下一个页面
if(isfirst){
//发送信息
handler.sendEmptyMessageDelayed(0,1000);
}else{
Intent intent = new Intent(MainActivity.this, ShowActivity.class);
startActivity(intent);
finish();
}
}
}