我正在提供一项服务,以随机的方式提醒用户。此服务由活动启动,并在后台作为服务运行。
我面临的挑战是,当用户将手机置于睡眠状态(空白屏幕)时,在某些情况下声音根本无法播放。时间已用完,但声音无法按时播放或在用户唤醒手机时播放。
以下是一些代码:
/**
* 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();
}
});
}
答案 0 :(得分:0)
在你的场景中无法获取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();
}