下面的代码在奥利奥之前一直有效,但是相同的代码在android pie中不起作用。请检查我的代码。
int audioFile = R.raw.ring;
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(this,
Uri.parse("android.resource://com.blh.pickupfresh.resturentapp/" + audioFile));
final AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_RING,audioManager.getStreamMaxVolume(AudioManager.STREAM_RING),0);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
mMediaPlayer.setLooping(true);
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
答案 0 :(得分:-1)
尝试此代码
int audioFile = R.raw.ring;
if(mMediaPlayer == null)
mMediaPlayer = new MediaPlayer();
try {
final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mMediaPlayer.setAudioAttributes(new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setLegacyStreamType(AudioManager.STREAM_MUSIC)
.build());
} else {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
mMediaPlayer.setLooping(true);
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
{
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mMediaPlayer.setDataSource(this, Uri.parse("android.resource://com.blh.pickupfresh.resturentapp/" + audioFile));
mMediaPlayer.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG,"ERROR=" + e.getMessage());
}
在这里,我使用了AudioManager.STREAM_MUSIC
,并且增加了同一视频流的音量。即使在静音模式或免打扰下,它也会播放声音。
更新:对于某些设备上的Android 9 mMediaPlayer.prepare()
,它需要花费几秒钟的时间,因此我们应将异步方法与回调及其工作结合使用。
在android系统中(至少是oreo + pie),当静音模式为开或 DND模式为开时,我们无法将AudioManager.STREAM_RING
设置为NORMAL,因为会抛出异常
java.lang.SecurityException: Not allowed to change Do Not Disturb state
。
详情请参见In Android 7 (API level 24) my app is not allowed to mute phone (set ringer mode to silent)