gpt4 book ai didi

java - 允许 App Timer 在屏幕锁定时运行

转载 作者:行者123 更新时间:2023-11-29 04:50:45 27 4
gpt4 key购买 nike

我正在为 Android 制作自己的运行应用程序,我有一个计时器,它应该使用 TextToSpeech 每 5 分钟宣布一次时间。我正在使用 Chronometer.OnChronometerTickListener 来跟踪时间并触发音频输出。当手机插入电脑时它工作正常,但当我拔下手机并锁定屏幕时,计时器听众似乎在大约 30 秒后进入休眠状态(因此音频不起作用)。有什么办法可以避免这种情况吗?

最佳答案

大多数时候,当屏幕关闭时需要做某事时,它是在服务中完成的。

enter image description here(www.slideshare.net)

假设您不知道什么是服务,根据文档:

A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use. Each service class must have a corresponding declaration in its package's AndroidManifest.xml. Services can be started with Context.startService() and Context.bindService().

所以基本上,它只是在后台运行的东西,包括屏幕关闭时。您可能会遇到服务被系统终止的问题,如 android 文档所述:

Note this means that most of the time your service is running, it may be killed by the system if it is under heavy memory pressure. If this happens, the system will later try to restart the service. An important consequence of this is that if you implement onStartCommand() to schedule work to be done asynchronously or in another thread, then you may want to use START_FLAG_REDELIVERY to have the system re-deliver an Intent for you so that it does not get lost if your service is killed while processing it.

在这种情况下,您将需要添加某些代码以将服务保持在前台并确保它不会被杀死:

startForeground();//keeps service from getting destroyed.

这可能提供的唯一问题是在服务处于 Activity 状态时不断发出通知。

您也可以使用 startSticky():

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}

现在,假设您已完成计时器。您可以使用:

stopSelf();

停止服务,或者:

Context.stopService();

虽然这个通知不是什么大问题,因为在服务运行时屏幕很可能是关闭的。您还可以自定义您的通知,更好地让用户知道后台发生了什么。

如果您需要更多帮助,请随时提出。

~鲁契尔

关于java - 允许 App Timer 在屏幕锁定时运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35516828/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com