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

时间:2015-07-03 23:20:27

标签: android android-studio android-service android-mediaplayer android-intentservice

带有计时器的Rx看起来像是要走的路。如果你不顺从它,Handler也可以工作。

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

1 个答案:

答案 0 :(得分:1)

你也可以使用任何计时器的想法,但我最有可能的做法是将beep封装在一个单独的Runnable类中,然后在需要的时候从我的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);
    }
}

然后在你的活动中,例如

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;
    }
}