Java 实施定期行动的适当方式
我需要每隔10秒从Android服务器上发送和接收一些东西。在这里,关于StackOverflow,在文档中,我发现了几十种实现它的方法(我尝试的每一种方法都能实现),但似乎到处都有人说这种方法有问题 我尝试了一个循环Java 实施定期行动的适当方式,java,android,service,scheduled-tasks,task,Java,Android,Service,Scheduled Tasks,Task,我需要每隔10秒从Android服务器上发送和接收一些东西。在这里,关于StackOverflow,在文档中,我发现了几十种实现它的方法(我尝试的每一种方法都能实现),但似乎到处都有人说这种方法有问题 我尝试了一个循环AsyncTask,直到它被取消(即直到活动被终止),我发现这不是一个好的解决方案。在此之前,我尝试使用常规的线程,然后发现它会消耗大量电池电量 现在,我已经使用Runnable和ScheduledExecutorService的scheduleAtFixedRate函数完成了这项
AsyncTask
,直到它被取消(即直到活动被终止),我发现这不是一个好的解决方案。在此之前,我尝试使用常规的线程
,然后发现它会消耗大量电池电量
现在,我已经使用Runnable
和ScheduledExecutorService的scheduleAtFixedRate
函数完成了这项工作,类似于这里提出的代码:
. 不用说,它是有效的。但是,如果我的活动是在后台进行的,例如,用户正在接听来电,它会起作用吗
最后,我不知道在安卓手机上最合适的方式是什么
Tnx提前。我想我会使用
Timer
类和TimerTask
:使用处理程序
它有多种方法,比如postDelayed(Runnable r,long delayMillis),posttime(Runnable r,Object token,long uptimeMillis)
等等
Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
//Start runnable here.
}
};
mHandler.sendMessageDelayed(msg, delayMillis)
如果您需要在应用程序当前未运行的情况下执行计划任务,建议使用和
否则,文档建议使用
如AmitD问题评论中所述。如果任务需要在后台运行,可以在处理程序回调中使用AsyncTask来实现这一点
final Handler handler = new Handler() {
public void handlerMessage(Message msg) {
new AsyncTask<TaskParameterType,Integer,TaskResultType>() {
protected TaskResultType doInBackground(TaskParameterType... taskParameters) {
// Perform background task - runs asynchronously
}
protected void onProgressUpdate(Integer... progress) {
// update the UI with progress (in response to call to publishProgress())
// - runs on UI thread
}
protected void onPostExecute(TaskResultType result) {
// update the UI with completion - runs on UI thread
}
}.execute(taskParameterObject);
}
};
handler.postMessageDelayed(msg, delayMillis);
执行重复任务在很大程度上取决于任务的规模/处理过程。用户界面将阻止您执行任务。如果是这样,则可以使用处理程序和TimerTask异步任务 在活动onCreate或任何通用函数中:
final Handler handler = new Handler();
timer = new Timer();
doAsynchronousTask = new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
handler.post(new Runnable() {
public void run() {
try {
// Instantiate the AsyncTask here and call the execute method
} catch (Exception e) {
e.printStackTrace();
}
}
});
timer.schedule(doAsynchronousTask,0,UPDATE_FREQUENCY)
}
任何周期性的时间都会耗尽电池,因为它永远不会让CPU(和系统)休眠是的,我尝试过,但如果传输持续时间稍长,它会滞后于UI。在handleMessage()中,您可以使用线程(完成后向处理程序发送另一条消息,以便更新UI)或在后台运行任务的AsyncTask。请尝试在handleMessage()内调用AsyncTask。那它就不会滞后于GUI了。谢谢你,这可能就是解决方法:)。
final Handler handler = new Handler();
timer = new Timer();
doAsynchronousTask = new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
handler.post(new Runnable() {
public void run() {
try {
// Instantiate the AsyncTask here and call the execute method
} catch (Exception e) {
e.printStackTrace();
}
}
});
timer.schedule(doAsynchronousTask,0,UPDATE_FREQUENCY)
}