我遇到了类似的问题.事实证明,当播放铃声时,它将无限重复直到停止,而当播放通知声音时,它将只播放一次.所以我的猜测是,你的情况的区别在于是否在someFunctionToLookupAValidNotificationRingtoneUri()中选择了铃声或通知声音.由于您没有提供someFunctionToLookupAValidNotificationRingtoneUri()的代码,我不知道那里发生了什么.
选择通知声音
如果您使用铃声选择器为用户选择通知声音,此代码将启动选择通知声音而不是铃声的意图:
private void PickANotificationSound() {
Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
// We want a notification sound picked. If we don't add this to the
// intent, a ringtone is picked; this means that when it is played,
// it will keep on playing until it is explicitly stopped. A
// notification sound, however, plays only once.
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE,
RingtoneManager.TYPE_NOTIFICATION);
// Start the intent to pick a notification sound. The result will show
// up later when onActivityResult() is called.
startActivityForResult(intent, REQUESTCODE_NOTIFICATION_SOUND);
}
其中REQUESTCODE_NOTIFICATION_SOUND只是一个具有任何名称和值的本地常量,用于标识请求:
private static final int REQUESTCODE_NOTIFICATION_SOUND = 1;
像这样的onActivityResult()回调函数将接收通知声音URI并播放它:
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == REQUESTCODE_NOTIFICATION_SOUND) {
try {
if (resultCode == RESULT_OK) {
Uri ringtoneUri = data.getParcelableExtra(
RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
if (ringtoneUri != null) {
PlayRingtoneOrNotificationSoundFromUri(ringtoneUri);
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else
super.onActivityResult(requestCode, resultCode, data);
}
private void PlayRingtoneOrNotificationSoundFromUri(Uri ringtoneUri) {
Ringtone ringtone = RingtoneManager.getRingtone(
getApplicationContext(), ringtoneUri);
if (ringtone != null) {
ringtone.play();
}
}
因为我们在意图中说我们想要选择通知声音,所以产生的声音是通知声音,因此仅在调用ringtone.play()之后播放一次.
如果我们在意图中说我们想要选择一个铃声,就像这样:
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE,
RingtoneManager.TYPE_RINGTONE);
选择器将返回一个铃声,该铃声将在ringtone.play()调用后无限期播放 – 直到被ringtone.stop()停止或应用程序被杀死.
‘铃声’的两个含义
请注意,Android API中的术语增加了混淆,因为单词“ringtone”使用了两种不同的含义(cf. the documentation of RingtoneManager):
>任何声音都是为了吸引用户的注意力,例如在手机响铃时反复播放的声音,通知声音或类似的声音.这个含义用在名称RingtoneManager中.>电话响铃时反复播放的声音,而不是通知声音或类似声音.这个含义在RingtoneManager.TYPE_RINGTONE中的名称TYPE_RINGTONE中使用.