微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

唤醒锁定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.我建议拿起他的书,不仅是为了详细解释这个课程和他在其中一个中包含的例子,而且还有他们在其中找到的其他丰富信息.

我刚刚为我的主应用程序实现了这个模式,这个类就像魅力一样.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐