【问题标题】:How to keep alive task into Foreground Service in standby / Doze mode?如何在待机/打盹模式下保持活动任务进入前台服务?
【发布时间】: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


【解决方案1】:

尝试请求用户验证您的应用以在后台运行

startActivity(new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, Uri.parse("package:" + getPackageName())));

【讨论】:

    猜你喜欢
    • 2018-10-30
    • 2017-08-06
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 2019-05-16
    • 1970-01-01
    • 1970-01-01
    • 2019-11-13
    相关资源
    最近更新 更多