唤醒锁定android服务重复出现
作者:互联网
我有这个应用程序需要运行定期发出蜂鸣声的服务(背景).
手机需要每隔一分钟发出一声哔哔声,持续5秒钟(在服务中使用了一个处理程序).我已经实现了这项完美的服务,但是当手机进入深度睡眠模式时,此处理程序的执行停止会停止.使用SO中的问题的this答案,我设法使用唤醒锁,它工作正常.但是当我明确地将手机置于深度睡眠模式时,处理程序停止执行.我在哪里将唤醒锁放在服务中.下面的代码片段.
public class PlaySound extends Service{
PowerManager.WakeLock wl ;
PowerManager pm;
private SoundManager mSoundManager;
boolean wakeUpFlag = false;
@Override
public void onCreate(){
super.onCreate();
mSoundManager = new SoundManager();
mSoundManager.initSounds(getBaseContext());
mSoundManager.addSound(1, R.raw.sound);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startservice();
return START_STICKY;
}
private void startservice() {
System.out.println("Started the service");
timer.scheduleAtFixedRate( new TimerTask() {
public void run() {
toastHandler.sendEmptyMessage(0);
}
}, 0, 60000);
}
private final Handler toastHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
result =start();
System.out.println("result"+result);
close();
}
};
protected void close() {
try {
if(wakeUpFlag){
wl.release();
System.out.println("Released the wakelock");
}
if(!pm.isScreenOn()){
System.out.println("Screen is off - back to sleep");
pm.goToSleep(1000);
}
else{
System.out.println("Screen is on - no need to sleep");
}
bs.close();
writer.close();
System.out.println("Closed socket and writer");
System.out.println("Size of file:"+f.length()/1024);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public void start(){
try{
wakeUpFlag = false;
pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
if(!pm.isScreenOn()) {
wakeUpFlag = true;
wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,"CollectData");
System.out.println("Screen off - wake lock acquired");
wl.acquire();
}
else{
System.out.println("Screen on - no need of wake lock");
}
}
catch(Exception e){
e.printStackTrace();
}
mSoundManager.playSound(1);
}
解决方法:
按照Mark Murphy提供的模式WakefulIntentService.我建议拿起他的书,不仅是为了详细解释这个课程和他在其中一个中包含的例子,而且还有他们在其中找到的其他丰富信息.
我刚刚为我的主应用程序实现了这个模式,这个类就像魅力一样.
标签:wakelock,android,service,android-service,handler 来源: https://codeday.me/bug/20190926/1821522.html