如何在Android应用程序中重复调用函数?

时间:2012-02-05 22:18:55

标签: java android multithreading time timer

我在我的Android应用程序中使用相机,我想每隔30秒拍一张照片。例如。对于间隔,我想使用先前时间和当前时间System.currentTimeMillis()或超时之间的差异。但我不知道如何重复调用函数。任何解决方案?

2 个答案:

答案 0 :(得分:2)

您需要多线程。如果你打电话给分机。活动,它使用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() {
        ...;
    }
};

答案 1 :(得分:1)

当你想要定期执行任何任务时,那么TimerTask类是最好的。结帐一个非常简单的示例here。在其运行方法中,您可以定期编写要执行的编码。您也可以在安排时给出时间间隔。