实施定期操作的正确方法 [英] Proper way of implementing a periodic action

查看:84
本文介绍了实施定期操作的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从一个服务器的Andr​​oid每隔10秒发送和拿东西。在这里,计算器,并在文档中,我发现几十个字面上的方式来实现它(和一切我试图做这项工作),但似乎无处不有人说什么是错用这种方式。

I have the need to send and take something from a server in Android on every 10 seconds. Here, on StackOverflow, and in the documentation I found literally dozens of ways to implement it (and everything I tried does the job), but it seems that everywhere someone says something is wrong with that way.

我试着用一个循环的AsyncTask ,直到它被取消(也就是直到活动被杀害),我发现,这不是一个很好的解决方案。在此之前,我试图用普通的主题,然后我发现它消耗电池电量不少。

I tried with a looping AsyncTask until it is canceled (that is untill the activity is killed), and I found out that it's not a good solution. Before that I tried with regular Threads, then I found out that it drains the battery a lot.

现在我已经有一个的Runnable 键,以及ScheduledExecutorService的的 scheduleAtFixedRate 功能,类似于$ C做了这里提出$ C:
<一href=\"http://stackoverflow.com/questions/6207362/how-to-run-an-async-task-afor-every-x-mins-in-android\">How在Android上运行的异步任务AFOR每x分钟?。不用说,它的工作原理。但如果我的行动是在后台运行,例如用户接听来电可以吗?

Now I've done it with a Runnable and and the ScheduledExecutorService's scheduleAtFixedRate function, similar to the code proposed here: How to run an async task afor every x mins in android? . Needless to say, it works. But will it work if my Activity is in the background, for example the user is answering an incoming call?

在结束时,我不知道了什么​​是做它在Android手机上的最正确的方法。

In the end, I don't know anymore what is the most proper way of doing it on an Android phone.

TNX提前。

推荐答案

使用处理程序它有多种方法,如 postDelayed(Runnable的R,长delayMillis ),postAtTime(Runnable的R,对象令牌,长uptimeMillis)等。

Use Handler it has various methods like postDelayed(Runnable r, long delayMillis),postAtTime(Runnable r, Object token, long uptimeMillis) etc.

Handler mHandler =  new Handler() {
    public void handleMessage(Message msg) {

      //Start runnable here.
    }
   };

mHandler.sendMessageDelayed(msg, delayMillis)

这篇关于实施定期操作的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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