【发布时间】:2016-02-02 12:49:41
【问题描述】:
我想知道如果我希望在标志为真时每五秒发生一次任务,我应该使用什么。我在安卓设备上运行它,所以性能很重要。
选项一是处理程序:
public void handleLocation() {
handler.postDelayed(new Runnable() {
public void run() {
Toast.makeText(mContext, "Five Seconds", Toast.LENGTH_SHORT).show(); // this method will contain your almost-finished HTTP calls
if (currentLocation != null && isWorking) {
setMockLocation(currentLocation);
setMockLocation2(currentLocation);
}
handler.postDelayed(this, FIVE_SECONDS);
}
}, FIVE_SECONDS);
}
第二个选项是线程:
public void run() {
Thread thread = new Thread() {
@Override
public void run() {
try {
while (true) {
if (isWorking) {
if (currentLocation != null)
setMockLocation(currentLocation);
setMockLocation2(currentLocation);
}
sleep(5000);
}
} catch (InterruptedException e) {
e.printStackTrace();
Toast.makeText(mContext, mContext.getString(R.string.err0_unknown), Toast.LENGTH_LONG).show();
}
}
};
thread.start();
}
你喜欢用什么?有没有更好的解决方案?
【问题讨论】:
-
为什么不使用while(flag)?
-
handler.postDelayed是首选选项,因为您还可以访问 UI 元素,这些元素执行 Thread 所需的任何额外代码。 -
@Peter 我还需要 UI 才能在后台运行。
-
@ρяσѕρєяK 我只需要在这个循环中设置MockLocation。 UI 在不同的线程中运行。它仍然是更可取的选择吗?
-
我的意思是结合睡眠。 :)
标签: java android multithreading android-handler