手机待机时不调用Handler.postDelayed
我正在尝试编写一个简单的应用程序,该应用程序应该在给定时间内将我的手机静音。这是我的第一个 Android 应用程序,但经过几个小时的阅读后,我认为它已接近完成。但它仍然有一个我无法解决的问题。
我正在使用一个活动来显示 GUI。它有按钮来设置开始和结束时间,以及其他所需的一切。当用户输入所有参数后,它们将被传递到服务。该服务使用一个处理程序对象来注册 2 个回调(使用 Handler.postDelayed)。一种用于开始静音,一种用于结束静音(在 SetMuteIntervall 中)。 第一次测试似乎有效,但如果我尝试将其静音 30 分钟,它永远不会取消静音。我认为这与手机处于或曾经处于待机模式有关。我还尝试使用 Handler.postAt() 但这也不起作用(并且相对于正常运行时间的时间有点令人困惑)。
那么,我应该怎么做才能保证无论手机是否处于待机状态,我的回调都会被调用呢?
这是我的程序的来源:
I'm trying to write a simple app that should mute my mobile phone for a given time. It's my first Android app, but after many hours of reading I think it is nearly completed. But it still has one problem that I can not fix.
I'm using a activity to display the GUI. It has Buttons to set the start and end time, and everything else needed. When the user has entered all the parameters, they are passed to a service. This service uses a handler object, to register 2 callbacks (with Handler.postDelayed). One for start Mute and one for End Mute (in SetMuteIntervall).
The first tests seemed to work, but if I try to mute it for like 30 minutes, it never unmutes. I think it has something to do with the fact, that the mobilephone is or was in standby mode. I also tried to use Handler.postAt() but that didn't work either (and time relative to uptime was somewhat confusing).
So, what should I do to guarantee, that my callbacks are called, regardless whether the phone is in standby or not?
Here's the source of my program:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试使用 AlarmManager 来计划将来的一些操作。 AlarmManager 不依赖于待机模式,即使设备处于睡眠状态也会触发。
您的线程实际上已停止,然后手机处于待机模式。如果您仍然想使用线程,您可以使用 WakeLock 来防止 CPU 进入待机模式(但仍会关闭屏幕),但这不是您的情况的最佳方法。
Try to use AlarmManager for planning some actions in future. AlarmManager is not standby-mode-dependend and will fire even if device is sleeping.
Your thread are actually stopped then the phone is in stand by mode. If you still want to use thread you can use WakeLock to prevent CPU from going to stand by mode (but still to switch screen off) but this is not the best way in your case.