android alarm manager sound after reboot

馋奶兔 提交于 2019-12-13 02:17:38

问题


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:


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();


来源:https://stackoverflow.com/questions/31454251/android-alarm-manager-sound-after-reboot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!