如何在Android中的延迟之后调用方法 [英] How to call a method after a delay in Android

查看:173
本文介绍了如何在Android中的延迟之后调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在指定的延迟之后调用下面的方法。  在Objective C中有这样的:

  [自performSelector:@selector(DoSomething的)withObject:无afterDelay:5]。
 

有没有这种方法的Andr​​oid与Java的等效? 例如,我需要能够在5秒后调用的方法。

 公共无效DoSomething的()
{
     //做的东西在这里
}
 

解决方案

它看起来像Mac OS的API,可以让当前线程继续,并调度任务异步运行。在Java中,同等功能是由的java.util.concurrent 封装。我不知道的Andr​​oid可能会强加什么限制。

 私有静态最后ScheduledExecutorService的工人=
  Executors.newSingleThreadScheduledExecutor();

无效的someMethod(){
  ⋮
  Runnable任务=新的Runnable(){
    公共无效的run(){
      /* 做一点事… */
    }
  };
  worker.schedule(任务,5,TimeUnit.SECONDS);
  ⋮
}
 

I want to be able to call the following method after a specified delay. In objective c there was something like:

[self performSelector:@selector(DoSomething) withObject:nil afterDelay:5];

Is there an equivalent of this method in android with java? For example I need to be able to call a method after 5 seconds.

public void DoSomething()
{
     //do something here
}

解决方案

It looks like the Mac OS API lets the current thread continue, and schedules the task to run asynchronously. In the Java, the equivalent function is provided by the java.util.concurrent package. I'm not sure what limitations Android might impose.

private static final ScheduledExecutorService worker = 
  Executors.newSingleThreadScheduledExecutor();

void someMethod() {
  ⋮
  Runnable task = new Runnable() {
    public void run() {
      /* Do something… */
    }
  };
  worker.schedule(task, 5, TimeUnit.SECONDS);
  ⋮
}

这篇关于如何在Android中的延迟之后调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆