允许 App Timer 运行 屏幕锁定时

Allow App Timer To Run When Screen Is Locked

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

大多数时候,当屏幕关闭时需要做某事时,它会在 service 中完成。

(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.

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

您也可以使用 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();

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

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

~Ruchir