用时间间隔致电ExectuorService -Android
我使用自定义线程通过使线程入睡一次,每1秒钟一次在后台获取数据,但是我的应用程序崩溃并抛出异常 Outofmemoryerror 。现在,我阅读了Android开发人员中的文档,我知道使用自定义线程是不好的练习,因为很难管理内存一致性。但是最后,当我们需要在后台执行一些任务时,我发现 executorService 非常有趣,所以我决定使用它。
如您所知,执行人员服务如下所示:
public void executeTask()
{
ExecutorService executroService = new Executor.newSingleThreadExecutor();
executroService.execute(new Runnable()
{
@Override
publi void run()
{
// now execute the server request
}
});
}
现在,我该如何达到每1秒钟的呼叫执行人员服务,直到用户转到onpause()状态,或者直到用户从当前活动转移到另一个活动?如果我使用自定义线程调用该服务,则该应用将崩溃。那我该如何实现呢?
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. 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. but finally i found ExecutorService very interesting when we need to do some tasks on background So, i decided to use it.
As You know the ExecutorService is like below:
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? if i use a custom thread to call that service, the App goes to crash. so how can i achive that ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要的是 scheduledexecutorservice
给定延迟
或定期执行。
这是一个实现此功能的代码
What you need is a ScheduledExecutorService
It can schedule commands to run after a given delay,
or to execute periodically.
Here is a code that implements this