相当于Android中的javax.swing.Timer

Dan*_*iel 4 java multithreading android timer

有什么东西看起来像javax.swing.Timer在Android上.我知道如何创建自己的Threads,但有什么东西就像swing-timer?

pop*_*tea 6

你可能正在寻找班级 android.os.CountDownTimer

你可以像这样继承这个类:

class MyTimer extends CountDownTimer
{
    public MyTimer(int secsInFuture) {
        super(secsInFuture*1000, 1000); //interval/ticks each second.
    }

    @Override
    public void onFinish() {
        Log.d("mytag","timer finished!");
    }

    @Override
    public void onTick(long millisUntilFinished) {
        //fired on each interval
        Log.d("mytag","tick; " + millisUntilFinished + " ms left");
    }
}
Run Code Online (Sandbox Code Playgroud)


Dan*_*les 1

还有Java的TimerTask。这是我的代码中播放音频样本的示例:

import java.util.Timer;
import java.util.TimerTask;

// from constructor, shown here out of place
timer = new Timer();

// and in method, again, shown out of place:
        INTERVAL_MILLISECONDS = (int)((double)(bufSize) / (double)(nativeSampleRate * 2) * 1000);
        timer.scheduleAtFixedRate( new TimerTask() {
                public void run() {
                        synchronized(this){
                                track.write(data, 0, bufSize);
                                track.play();
                        }
                }
        }, 0, INTERVAL_MILLISECONDS);
Run Code Online (Sandbox Code Playgroud)