【发布时间】:2019-09-14 15:04:19
【问题描述】:
我有一个前台服务,它根据任务中的每个 1 来管理一些计时器计数器。但是,在待机模式或打盹模式,任务由系统切换到暂停。这种行为并非在所有手机上都存在,但在华为上,小米经常出现。
你们有什么想法可以解决这个问题吗?
非常感谢
我的服务:
public class MyTimerService extends Service {
@SuppressLint("WakelockTimeout")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent == null) return START_STICKY_COMPATIBILITY;
// First at all, generate system notification with foreground link
createNotification();
...
mExecutorFuture = MyApplication.getInstance().getExecutorServiceScheduler().
scheduleWithFixedDelay(() -> {
lockCPU()
...
unlockCPU()
}
}, 0, 1/* every 1 second*/, TimeUnit.SECONDS);
}
return START_STICKY;
}
private void lockCPU() {
PowerManager mgr = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
mWakeLock.acquire();
}
@Override
public void onDestroy() {
resetSound();
super.onDestroy();
...
if (mExecutorFuture != null) {
mExecutorFuture.cancel(true);
}
}
private void unlockCPU() {
if (mWakeLock != null && mWakeLock.isHeld()) {
mWakeLock.release();
mWakeLock = null;
}
}
【问题讨论】:
-
你每一秒究竟在做什么?
-
我处理了一些计时器,并根据我向 UI 发送事件 (EventBus) 的值并播放声音(bip 计时器)。
-
除非你每秒都在发出哔哔声,否则应该有更有效的方法,而不是每秒获得控制权(并保持 CPU 开启)。一般来说,用户不喜欢浪费电量的应用程序,一些制造商相当积极地阻止应用程序在后台持续运行。正如唐克所指出的,您可以尝试让用户将您的应用添加到电池优化白名单中,但这并不能保证有帮助。
-
不,白名单不起作用。我试过了。
标签: android foreground