如何在API低于28的情况下为铃声实例启用循环?

3
我有以下方法
    private void playRingtone() {
        Uri sound = Uri.parse(Constants.ANDROID_RESOURCE_ROOT + this.getPackageName() +
                Constants.SLASH_SEPARATOR + R.raw.sound);
        this.ringtone = RingtoneManager.getRingtone(this.getApplicationContext(), sound);
        this.ringtone.setLooping(Boolean.TRUE);
        this.ringtone.play();
    }

在调用 setLooping(Boolean.TRUE); 方法时,会出现以下提示信息:

调用需要 API level 28(当前最低的 min 版本为 21):android.media.Ringtone#setLooping

在 API 版本低于 28 的情况下,Ringtone 实例是否有其他方法可以替代 setLooping 呢?


我在这里查看了(https://developer.android.com/reference/kotlin/android/media/Ringtone),似乎不可能。 - FailingCoder
1
你为什么要专门创建一个 Ringtone 对象呢?难道不能使用 MediaPlayer 吗?例如:MediaPlayer player = MediaPlayer.create(this, sound);player.setLooping(true);player.start(); - Mike M.
2个回答

3
你可以尝试在 scheduleAtFixedRate 中添加一个timerTask 来检查它是否还在播放。
具体做法如下:
Timer timer = new Timer(); 
timer.scheduleAtFixedRate(new TimerTask() {
    public void run() {
        if (!this.ringtone.isPlaying()) {
            this.ringtone.play();
        }
    }
}, 1000, 100);

在这里,1000 是计时器开始运行的时间,而 100 是时间间隔。

希望这有所帮助。


那么,Timer 作为一个 **Thread**,是吗? 但是,在这种情况下,这个 TimerTask 是否会无限运行?或者我可以设置一个限制吗? - José María
你可以通过在内部添加递增值或只是添加一个监听器或其他东西来停止线程,从而添加限制。 - Francis G

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接