您的位置:首页 > 其它

Handler和Timer实现倒计时跳转页面

2017-06-19 20:40 344 查看
   我们在app的导航页应用到倒计时3秒进入主页,并且是第一次进入的时候显示该导航页,第二次进入的时候直接进入主页

   此处我们可以使用handler+sharedpreferences 或者timer+sharedpreferences实现效果

  话不多说,直接上代码

  

   首先,我们简单的写两个activity的布局,用于跳转



简单的写一个textview用于显示倒计时秒数

public class StartActivity extends AppCompatActivity {

private TextView jump;

    private SharedPreferences mSp;
    private SharedPreferences.Editor mEdit;
Timer timer=new Timer(); //利用timer实现倒计时跳转  
         int c=3;     

TimerTask task=new TimerTask() {         

@Override         

        public void run() {             

runOnUiThread(new Runnable() {     //子线程不能更新UI,将逻辑写在runOnUiThread内
@Override                 

                   public void run() {                     

                      jump.setText("还有"+c+"秒跳转");                  

c--;                       //定义一个变量c作为倒计时间                     

                           if (c<0){                         

                             timer.cancel();         //利用Intent实现跳转                         

Intent intent = new Intent(StartActivity.this, MainActivity.class);                         

startActivity(intent);                         

finish();                    

}                

}             

});        

}     };


Handler handler=new Handler(){      //利用handler实现倒计时跳转
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
jump.setText("还有"+c+"秒跳转");
c--;
if (c<0){

Intent intent = new Intent(StartActivity.this, MainActivity.class);
startActivity(intent);
finish();
}else {                            //倒计时间<0秒时进行跳转,否则继续发消息进行更新UI
handler.sendEmptyMessageDelayed(0,1000);
}
mEdit.putBoolean("first",false);    //sharedpreferences存第一次进入该界面的boolean状态值
mEdit.commit();
break;

default:
break;
}
}
};


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

timer.schedule(task,1000,1000);

mSp = getSharedPreferences("first", MODE_PRIVATE);   //初始化sp对象
boolean first = mSp.getBoolean("first", true);       //取sp的值,如果是true,代表第一次进入,否则直接跳转
if (first){
handler.sendEmptyMessageDelayed(0,1000);
}else {
Intent intent = new Intent(StartActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
mEdit = mSp.edit();               //初始化sp编辑器edit对象

}

private void initView() {
jump = (TextView) findViewById(R.id.jump);  //根据ID找控件
}
}



我用两种方式都可以实现倒计时效果,是不是so easy!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: