【问题标题】:How I can avoid the device from going to sleep mode?, even using a wakelock如何避免设备进入睡眠模式?,即使使用唤醒锁
【发布时间】:2016-04-08 15:17:52
【问题描述】:

我的 Android 应用程序上有一项服务,当我的应用程序中的用户会话处于活动状态时,该服务每 20 秒在我的服务器中发布一次。

如果我的设备连接到电源,这在几天内运行正常,但如果设备断开连接且未使用(屏幕关闭),服务似乎停止但几分钟后再次开始运行并继续运行小时。

在服务中,我使用wakelock来避免设备进入睡眠模式。

对不起,我的英语太基础了

【问题讨论】:

    标签: android service android-wake-lock


    【解决方案1】:

    问题是我正在使用 Android 版本 6 的设备上进行测试,为此我们必须使用 setAlarmClock 来唤醒设备。

            Intent intent = new Intent(context, MyWakefulBroadcastReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
    
            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    
            long triggerAtMillis = System.currentTimeMillis() + 20 * 1000;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                AlarmManager.AlarmClockInfo alarmClockInfo = new AlarmManager.AlarmClockInfo(triggerAtMillis, pendingIntent);
                alarmManager.setAlarmClock(alarmClockInfo, pendingIntent);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                alarmManager.setExact(android.app.AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent);
            } else {
                alarmManager.set(android.app.AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent);
            }
    

    【讨论】:

      【解决方案2】:

      因为当您的活动被终止时,您的服务也被终止。如果您希望您的服务仍在运行,请不要使用 Context.bindService() 来启动它,而是使用 Context.startService()。有关更多详细信息,请查看此链接How to start your service 并了解有关服务的所有信息http://developer.android.com/reference/android/app/Service.html

      【讨论】:

        猜你喜欢
        • 2022-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-27
        • 2014-11-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多