AndroidStudio - 如何添加循环和延迟(以分钟为单位)

时间:2015-11-26 20:52:47

标签: java android loops android-studio delay

我有以下无效:

public void onClick(View v) 
{
    PostDataTask postDataTask = new PostDataTask();

    postDataTask.execute(URL,textView3.getText().toString(),textView5.getText().toString(),textView12.getText().toString(),textView13.getText().toString(),textView14.getText().toString(),textView7.getText().toString(),textView15.getText().toString());

}

我想循环播放" postDataTask.execute(...)"因此它将每30分钟执行24小时(因此总共执行48次)。有人可以帮我这个吗?

*编辑

所以我使用了第一个建议,但它只运行1次60秒。是因为它在onCreate中有类吗? :

@Override
protected void onCreate(Bundle savedInstanceState) {
    final PostDataTask postDataTask = new PostDataTask();
    final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    final Runnable exec = new Runnable() {
        public void run() {
            postDataTask.execute(URL, textView3.getText().toString(), textView5.getText().toString(), textView12.getText().toString(), textView13.getText().toString(), textView14.getText().toString(), textView7.getText().toString(), textView15.getText().toString());

        }
    };

    final ScheduledFuture execHandle = scheduler.scheduleAtFixedRate(exec, 60, 60, SECONDS);
    scheduler.schedule(new Runnable() {
        public void run() {
            execHandle.cancel(true);
        }
    }, 60 * 60, SECONDS);

1 个答案:

答案 0 :(得分:0)

ScheduledExecutorService可以做到这一点。

使用示例

这是一个类,其方法设置ScheduledExecutorService每隔十秒钟发出一声哔声:

 import static java.util.concurrent.TimeUnit.*;
 class BeeperControl {
   private final ScheduledExecutorService scheduler =
     Executors.newScheduledThreadPool(1);

   public void beepForAnHour() {
     final Runnable beeper = new Runnable() {
       public void run() { System.out.println("beep"); 
     };
     final ScheduledFuture beeperHandle =
       scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
     scheduler.schedule(new Runnable() {
       public void run() { beeperHandle.cancel(true); }
     }, 60 * 60, SECONDS);
   }
 }}

Code from ScheduledExecutorService documentation