【问题标题】:Run a method only for 10 seconds asynchronously android只异步运行一个方法10秒android
【发布时间】:2018-09-11 02:48:39
【问题描述】:
我有一组动作或函数,它们只需要在特定的时间内执行,比如 X 秒。如果我可以在指定的时间内完全执行功能,我如何才能完成这项任务并显示成功或失败。
我不想在执行激活时阻止 Android UI。在使用 getCurrentTime() 时尝试使用 do 但这会阻止 UI。
【问题讨论】:
标签:
java
android
multithreading
future
threadpoolexecutor
【解决方案1】:
在活动类文件中:
private boolean status = false; //set a initial flag
private Handler customHandler;
customHandler = new Handler();
Runnable currentThreadTask = new Runnable() {
@Override
public void run() {
status = customfunction();
//call your function,suppose the function executed successfully,'status' changed to ture.
}
};
customHandler.post(currentThreadTask);
public boolean customfunction(){
//Time consuming operations
return true;
}
并创建一个countDownTimer,像这样:
new CountDownTimer(5000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {//5 seconds passed
//Check 'status' value
//If status is still equal false,then customfunction executed failed in 5 seconds
//otherwise it successed.
}
}.start();