这是我的活动:
public class AlarmPlayerActivity extends AppCompatActivity implements MediaPlayer.OnPreparedListener {
private MediaPlayer player;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm_player);
int alarm_number = getIntent().getIntExtra(Config.KEY_ALARM_NO, 0);
((TextView) findViewById(R.id.alarm_message)).setText(getString(R.string.alarms_was_set).concat(": " + alarm_number));
}
public void stopPlayingAlarm(View view) {
if (player != null && player.isPlaying()) {
player.reset();
player.stop();
player.release();
}
}
@Override
protected void onStart() {
super.onStart();
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
player = MediaPlayer.create(this, uri);
player.setAudioStreamType(AudioManager.STREAM_ALARM);
player.setLooping(true);
player.setOnPreparedListener(this);
player.prepareAsync();
}
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
}
但是它会在IllegalStateException
通话中抛出player.prepareAsync()
。
尽管我已经尝试过在此站点中找到其他答案,但我无法修复它。
请注意,此活动是从RTC_WAKEUP
警报触发的广播接收器启动的。
这是我的AndroidManifest的一部分:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.EXPAND_STATUS_BAR" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
答案 0 :(得分:2)
您好,回答晚了,但我认为您需要更多支持@Miller回答的解释。
您正在使用static MediaPlayer create (Context context, Uri uri)
方法创建 MediaPlayer 实例。此方法将通过自己调用prepare()
为您分配audioSessionId。
Note that since prepare() is called automatically in this method, you cannot change the audio session ID
很显然,您不能编辑其audioSessionID。而当您致电player.prepareAsync();
时,它会请求新的sessionId。结果为illegalStateException
。 see docx
答案 1 :(得分:1)
MediaPlayer已在其中包含prepare()。因此,如果您调用第二个prepare(),它将抛出异常。