Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
87 views
in Technique[技术] by (71.8m points)

android - How do I run code in the background, even with the screen off?

I have a simple timer app in Flutter, which shows a countdown with the number of seconds remaining. I have:

new Timer.periodic(new Duration(seconds: 1), _decrementCounter);

It seems to work fine until my phone's display switches off (even if I switch to another app) and goes to sleep. Then, the timer pauses. Is there a recommended way to create a service that runs in the background even when the screen is off?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Answering the question of how to implement your specific timer case doesn't actually have to do with background code. Overall running code in the background is something discouraged on mobile operating systems.

For example, iOS Documentation discusses background code in greater detail here: https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html

Instead mobile operating systems provide apis (like a timer/alarm/notification apis) to call back to your application after a specific time. For example on iOS you can request that your application be notified/woken at a specific point in the future via UINotificationRequest: https://developer.apple.com/reference/usernotifications/unnotificationrequest This allows them to kill/suspend your app to achieve better power savings and instead have a single highly-efficent shared system service for tracking these notifications/alarms/geofencing, etc.

Flutter does not currently provide any wrappers around these OS services out-of-the-box, however it is straighforward to write your own using our platform-services model: flutter.io/platform-services

We're working on a system for publishing/sharing service integrations like this so that once one person writes this integration (for say scheduling some future execution of your app) everyone can benefit.

Separately, the more general question of "is it possible to run background Dart code" (without having a FlutterView active on screen), is "not yet". We have a bug on file: https://github.com/flutter/flutter/issues/3671

The use-case driving that kind of back-ground code execution is when your app receives a notification, wants to process it using some Dart code without bringing your app to the front. If you have other use cases for background code you'd like us to know about, comments are most welcome on that bug!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...