Here is my Activity:
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();
}
}
But it throws IllegalStateException
on player.prepareAsync()
call.
I cannot fix it although I have tried other answers found in this site.
Note that, this activity is launched from a broadcast receiver which is triggered by an RTC_WAKEUP
alarm.
Here is part of my 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"/>
MediaPlayer already had prepare() inside. So if you call a second prepare(), it will throw exception.