【问题标题】:Call Particular Method after regular interval of time在固定时间间隔后调用特定方法
【发布时间】:2011-06-04 11:56:01
【问题描述】:

在我的 android 应用程序中,我想定期调用特定的方法,即。 “每 5 秒后”......我该怎么做......?

【问题讨论】:

    标签: android android-2.2-froyo


    【解决方案1】:

    您可以将Timer 用于方法的固定周期执行。

    这是一个代码示例:

    final long period = 0;
    new Timer().schedule(new TimerTask() {
        @Override
        public void run() {
            // do your task here
        }
    }, 0, period);
    

    【讨论】:

      【解决方案2】:

      上面的这个链接已经过测试并且工作正常。这是每秒调用某个方法的代码。您可以将 1000(= 1 秒)更改为您想要的任何时间(例如 3 秒 = 3000)

      public class myActivity extends Activity {
      
      private Timer myTimer;
      
      /** Called when the activity is first created. */
      @Override
      public void onCreate(Bundle icicle) {
          super.onCreate(icicle);
          setContentView(R.layout.main);
      
          myTimer = new Timer();
          myTimer.schedule(new TimerTask() {          
              @Override
              public void run() {
                  TimerMethod();
              }
      
          }, 0, 1000);
      }
      
      private void TimerMethod()
      {
          //This method is called directly by the timer
          //and runs in the same thread as the timer.
      
          //We call the method that will work with the UI
          //through the runOnUiThread method.
          this.runOnUiThread(Timer_Tick);
      }
      
      
      private Runnable Timer_Tick = new Runnable() {
          public void run() {
      
          //This method runs in the same thread as the UI.               
      
          //Do something to the UI thread here
      
          }
      };
      }
      

      【讨论】:

      • 谢谢。为我工作。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-06
      • 2011-01-20
      相关资源
      最近更新 更多