android alarm manager sound after reboot

2019-08-09 02:09发布

I'm working on a service-like application using android's AlarmManager. The app basically connects to a server and calls a remote procedure. If the value returned is True, it plays a sound:

MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING); 
try {
    mediaPlayer.setDataSource(getApplicationContext(), 
     Uri.parse("file:///system/media/audio/ringtones/Rolling_tone.ogg"));
}
...
mediaPlayer.start();

This works all and well when the application is started manually. However when the phone is rebooted (I've implemented the BroadcastReceiver), the sound is played for like a second then gets interrupted immediately.

It sounds almost like the play cycle is being cut off by something. I need to stop and re-start the application to have it working correctly again.

Any clues on what the cause could be?

1条回答
虎瘦雄心在
2楼-- · 2019-08-09 02:45

You could use MediaPlayer's setScreenOnWhilePlaying() to ensure that your application doesn't go to sleep while the audio plays in the background.

http://developer.android.com/reference/android/media/MediaPlayer.html#setWakeMode%28android.content.Context,%20int%29

Another possible solution is the use the PowerManager to keep your device awake with a WakeLock:

See http://developer.android.com/reference/android/os/PowerManager.html

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
wl.acquire();
   ... wait until sound has finished playing (with listener)
wl.release();
查看更多
登录 后发表回答