Android之定时刷新数据

近期项目,要求定时刷新访问服务器获取状态,经查资料,了解到几种定时刷新数据的方式
常见的定时刷新有:Timer、 Alarm、Handle  
widgetapp更新中常用Alarm用的比较多,但有说用alarm会使系统反应变慢,由于急于完成项目,故未验证此方法。个人开发中常用Timer做开机动画的延时,
另外,在定时刷新网络时常用Handle,以下是定时刷新的用法:
1.Timer的用法
用法一:<个人并未使用这种方法>
private Timer timer = new Timer();


TimerTask task = new TimerTask(){
           public void run(){
                    Message message = new Message();
   handler.sendMessage(message);
          }


};
Handler handler = new Handler(){
public void handleMessage(Message msg){
switch(msg.what){
    case 1:
update()//要更新的数据可放在这里
break;
}
}
}
用法二:<个人常用此方法做开机动画>
Timer timer = new Timer();
//参数1:TimerTask 参数2:定时时间,单位毫秒
timer.schedule(new TimerTask(){
@Override
public void run(){
Intent intent = new Intent(AA.this,BB.class);
startActivity(intent);
}

},3000);
2.Alarm的用法<未使用过>
  开始计时:
Intent intent = new Intent(widgetUpdate);
        refreshIntent = PendingIntent.getBroadcast(pContext,0,intent,0);
alarm = (AlarmManager)pContext.getSystemSerVice(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.PTC,0,1000,refreshIntent);//每秒刷新一次
停止计时:
if (alarm!=null) {
     alarm.cancel(refreshIntent);
     refreshIntent.cancel();
     refreshIntent = null;
  alarm = null;
}
3.Handler<刷新网络使用,简单实用>


 private Handler handler  = new Handler();
private Runnable runnable = new Runnable(){
public void run(){
update();//更新数据
handler.postDelayed(this,1000);//定时时间
}
};
开始计时:
handler.removeCallbacks(runnable);
handler.postDelayed(runnable,1000);


停止计时:
handler.removeCallbacks(runnable);


引用博客:特此感谢该博主


http://blog.csdn.net/itxiaohei323/article/details/7875953
  • 1
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值