我在 Android 应用程序中使用相机,我想每 30 秒拍一张照片。例如。对于间隔,我想使用前一个时间和当前时间之间的差异 System.currentTimeMillis() 或超时。但我不知道如何使函数被重复调用。有什么解决办法吗?
最佳答案
你需要多线程。如果您调用分机。 Activity,它使用UI,所以你不应该使用Timer。仅处理程序。许多用于多线程的 java 类不适用于 Android UI。使用这个类:
import android.os.Handler;
/**
* Examples of use:
*
* Waiter(Runnable call, 30000); - in the calling method
*
* @author Petr Gangnus
*/
public class Waiter {
/**
* the handler that works instead of timer and supports UI
*/
static private Handler handler = new Handler();
Runnable task;
public Waiter(Runnable task,long time){
this.task=task;
handler.removeCallbacks(task);
handler.postDelayed(task, time);
}
public void stopWaiting(){
handler.removeCallbacks(task);
}
}
// setting the task called - in the calling method
final private Runnable call = new Runnable() {
@Override
public void run() {
...;
}
};
关于java - 如何在Android应用程序中重复调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9153606/