Handler倒计时
程序员文章站
2022-07-14 17:06:00
...
public class MainActivity extends AppCompatActivity {
private TextView text_time;
private Button but_1;
private int i = 5;
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.what==0){
if (i==0){
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
finish();
}else{
i--;
text_time.setText(i+"秒");
handler.sendEmptyMessageDelayed(0,1000);
}
}
}
};
private SharedPreferences sp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取控件
text_time = findViewById(R.id.text_time);
but_1 = findViewById(R.id.but_1);
//获取getSharedPreferences
sp = getSharedPreferences("key",MODE_MULTI_PROCESS);
//判断
if(sp.getBoolean("key",false)){
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
}
//提交
sp.edit().putBoolean("key",true).commit();
//点击跳转
but_1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
}
});
//发送消息
handler.sendEmptyMessageDelayed(0,1000);
}
}