Java 建议更好的线程处理方法
如果方法正确,请检查步骤1和2。另外,建议如何编写步骤2 问题陈述: 1。启动正在进行的线程以捕获应用程序的状态。Java 建议更好的线程处理方法,java,android,Java,Android,如果方法正确,请检查步骤1和2。另外,建议如何编写步骤2 问题陈述: 1。启动正在进行的线程以捕获应用程序的状态。 Thread thread = new Thread() { public void run() { while (true) { try { checkStaus(); Thread.sleep(TIMER); // 1 mins } catch
Thread thread = new Thread() {
public void run() {
while (true) {
try {
checkStaus();
Thread.sleep(TIMER); // 1 mins
} catch (InterruptedException e) {
Log.e("MyService", "local Thread error", e);
}
}
}
};
thread.start();
2。10分钟后,将捕获的日志发送到服务器。
Thread thread = new Thread() {
public void run() {
while (true) {
try {
checkStaus();
Thread.sleep(TIMER); // 1 mins
} catch (InterruptedException e) {
Log.e("MyService", "local Thread error", e);
}
}
}
};
thread.start();
伪:
a。保持计数器,直到达到600000毫秒(10分钟)
b。启动异步任务以将捕获的日志发送到服务器
c。成功发送文件后,重置计数器;清空日志文件并继续捕获日志
谢谢
- 要修复:
删除
并将其替换为类似while(true)
的布尔值。在while(isRunning)
中,将ondestory()
设置为falseisRunning
IntentService
而不是AsyncTask
IntentService
是一个非常方便的工具,专门用于这类事情。您可以将计时器设置为每10分钟运行一次,然后启动IntentService
将日志发送到服务器。它将在后台运行,如果用户离开应用程序,您不必担心被系统转储或内存泄漏Write logs to `File1`
At ten minutes, start `IntentService`. Pass the name of the file in the `Intent` used to start it`
Start writing logs to `File2`
在IntentService
Get file name for file to send in the Intent
Send file to server
On completion, delete file
使用TimerTask,如下所示:
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
// ... stuff
boolean run_again = ??? /// end infinite loop or not .. you should set this somewhere
if (run_again)
timer.schedule(this, 600000);
}
}
timer.schedule(task, 600000); // or 0 if you want to run it right away first
语法可能有点脱离记忆谢谢您的快速响应。I.我正在考虑在一个
IntentService
中运行整个操作,因此它将不会连接到任何活动,因此您是否认为建议1仍然是必需的。二,。如建议2所示,那么可以在另一个IntentService中启动一个新的IntentService吗?IntentService的问题是它们在队列中运行。这意味着一个人在完成之前不会开始。它们不打算运行10分钟。如果您需要从活动中收集统计信息,那么IntentService将是首选方法。如果完全可以从服务中收集它们,那么您最好只是启动一个服务并从中运行一个通用线程。我认为情况正好相反。IntenetService可以用于更长时间的持续任务,而不是服务。请建议,因为我现在很困惑。但是对于并行IntentService,我同意你的看法。你完全可以在长时间运行的操作中使用IntentService,但是如果你想运行更多的操作,它会阻塞队列(你现在不需要,但以后可能需要)。现在我想了想,我不确定每个IntentService类是否都有一个队列,或者整个应用程序是否只有一个IntentService队列。