[英]Call ExectuorService with time interval - android
i used a custom thread to fetch data in the background every 1 second by making a thread goes to sleep, but my App crashes and throws exception OutOfMemoryError .我使用自定义线程通过使线程进入睡眠状态每 1 秒在后台获取数据,但是我的应用程序崩溃并抛出异常OutOfMemoryError 。 Now i read a documentation in android developer and i understand that using custom thread is bad practice as it is difficult to manage the memory consistency.
现在我阅读了 android developer 中的文档,我明白使用自定义线程是不好的做法,因为很难管理内存一致性。 but finally i found ExecutorService very interesting when we need to do some tasks on background So, i decided to use it.
但最后我发现ExecutorService非常有趣,当我们需要在后台执行一些任务时,我决定使用它。
As You know the ExecutorService is like below:如您所知,ExecutorService 如下所示:
public void executeTask()
{
ExecutorService executroService = new Executor.newSingleThreadExecutor();
executroService.execute(new Runnable()
{
@Override
publi void run()
{
// now execute the server request
}
});
}
Now how can i achive calling to executorService every 1 second untill the user goes to onpause() state or untill the user shifts from the current activity to another activity?现在我如何才能每 1 秒调用一次 executorService 直到用户进入 onpause() 状态或直到用户从当前活动转移到另一个活动? if i use a custom thread to call that service, the App goes to crash.
如果我使用自定义线程调用该服务,应用程序会崩溃。 so how can i achive that ?
那我怎么能做到呢?
What you need is a ScheduledExecutorService你需要的是一个ScheduledExecutorService
It can schedule commands to run after a given delay, or to execute periodically.它可以安排命令在给定延迟后运行,或定期执行。
Here is a code that implements this这是实现此功能的代码
import static java.util.concurrent.TimeUnit.*;
class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
Runnable beeper = () -> System.out.println("beep");
ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
Runnable canceller = () -> beeperHandle.cancel(false);
scheduler.schedule(canceller, 1, HOURS);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.