在实际开发中更多的是需要我们实时获取最新数据,比如道路流量、实时天气信息等,这时就需要通过一个线程来控制视图的更新。

示例:我们首先创建一个网页来显示系统当前的时间,然后在Android程序中每隔5秒刷新一次视图,以达到实时更新的效果。

在Android中,更新视图不能直接在线程中进行,所以需要使用Handler来实时更新。

在onCreate方法中执行语句:

new Thread(mRunnable).start();

在onCreate方法外定义mRunnable

Runnable mRunnable = new Runnable() {

  public void run(){

    while(true){

      try{Thread.sleep(5*1000);}catch(InterruptedException e){}

      mHandler.sendMessage(mHandler.obtainMessage());

    }

  }

});

在onCreate方法外定义mHandler

  Handler mHandler = new Handler(){

    public void handleMessage(Message msg) {

      refresh(); // 在refresh方法中更新视图上

    }

  };

相关文章:

  • 2022-01-09
  • 2021-06-11
  • 2021-05-30
  • 2021-08-08
  • 2021-09-06
  • 2022-02-17
  • 2022-12-23
  • 2021-05-13
猜你喜欢
  • 2021-11-24
  • 2022-01-31
  • 2021-09-15
  • 2022-12-23
  • 2021-12-01
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案