Android - 在背景中重复声音 X 次,每次延迟 Y

Android - Repeat sound in background X times with a Y delay each time

带计时器的 Rx 看起来是个不错的选择。如果您不喜欢它,Handler 也可以工作。

http://reactivex.io/documentation/operators/timer.html

你也可以使用任何计时器的想法,但我最有可能做的是将蜂鸣声封装在一个单独的 Runnable class 中,然后在需要时从我的 activity/fragment/view 中调用它。

public final class BeepRunnable implements Runnable {
    private final MediaPlayer mediaPlayer;
    private final View view;
    private final int repeats;
    private final int interval;
    private int currentRepeat;

    public BeepRunnable(@NonNull View view, int repeats, int interval) {
        this.view = view;
        mediaPlayer = MediaPlayer.create(this.view.getContext(), R.raw.beep);
        this.repeats = repeats;
        this.interval = interval;
    }

    @Override
    public void run() {
        mp.start();
        if (currentRepeat < repeats) {
            // set to beep again
            currentRepeat = currentRepeat + 1;
            view.postDelayed(this, interval);
        }
        else {
            // beep is over, just reset the counter
            reset();
        }
    }

    public void reset() {
        currentRepeat = 0;
    }

    public void destroy() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }

        mediaPlayer.release();
        view.removeCallbacks(this);
    }
}

然后以你activity为例

public final ApplicationActivity extends Activity {
    private BeepRunnable beepRunnable;
    ...
    // in your place where you need to start the beeping
    beepRunnable = new BeepRunnable(anyNonNullView, 4, 500);
    anyNonNullView.post(beepRunnable);
}

public void onDestroy() {
    super.onDestroy();

    if (beepRunnable != null) {
        beepRunnable.destroy();
        beepRunnable = null;
    }
}