我正在编写一项以随机间隔提醒用户的服务。该服务由 Activity 启动,并作为服务在后台运行。
我面临的挑战是,当用户将手机置于睡眠状态(黑屏)时,在某些情况下根本不会播放声音。时间已用完,但声音既不会按时播放,也不会在用户唤醒手机时播放。
这是一些代码:
/**
* 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();
}
});
}