手机睡觉时播放声音
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了手机睡觉时播放声音相关的知识,希望对你有一定的参考价值。
我正在写一个服务,以随机的间隔提醒用户。此服务由活动启动,并在后台作为服务运行。
我面临的挑战是,当用户将手机置于睡眠状态(空白屏幕)时,在某些情况下声音根本无法播放。时间已用完,但声音无法按时播放或在用户唤醒手机时播放。
这是一些代码:
/**
* Starts a new thread which is checking every seconds how much time has
* elapsed and if the point of time has come to play the sound.
* Once the time has come, it gets the next ring time and continues
* until it is shut down by the user
*/
private void runCheck() {
Log.i(tag, "starting runCheck");
Thread thread = new Thread() {
public void run() {
Log.i(tag, "starting LogoTimerThread");
while (vRunningFlag) {
try {
// update the notification
makeNotification();
Log.v(tag,
"Next Ring in : ["
+ helper.TimeCalculator
.duration2_hh_MM_SS((vTimerNextRing - System
.currentTimeMillis()) / 1000)
+ " sec.]");
// check if time has run out
if (vTimerNextRing < System.currentTimeMillis()) {
// reset the timer
setNextRingTime();
// update the screen
makeNotification();
// play the sound
playLTimerSound();
}
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Log.i(tag, "finished LogoTimerThread");
}
};
thread.start();
}
整个服务作为远程服务运行,设置为前台,因此通知会提醒用户该服务,并且他可以这样停止。
一旦我评论出playLTimerSound()
,计时器就会倒计时。不知何故,线程通过播放声音而停止。
这也是这个功能:
public void playLTimerSound() {
Log.i(tag, "playLogoTimerSound - volume:" + vVolume);
MediaPlayer mp = MediaPlayer.create(this, R.raw.enterprise);
mp.setVolume(2.0f, 2.0f);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
}
答案
在你的场景中无法获取SCREEN_DIM_WAKE_LOCK?
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "App");
wl.acquire();
}
以上是关于手机睡觉时播放声音的主要内容,如果未能解决你的问题,请参考以下文章
播放android studio时片段中的VideoView没有声音