I want to play 1 (or more) scheduled short audio bells in the executeTask callback from the workmanager package when the user puts in the app in the background.
executeTask callback always fires when it should. However -- the audio does not play consistently when run in this callback. It only sometimes plays. But usually it just doesn't play. There are no errors either. I therefore suspect there is an issue with using async methods in the callback.
AudioPlayer player = AudioPlayer();
@pragma('vm:entry-point')
void callbackDispatcher() {
Workmanager().executeTask((task, inputData) async {
print("Native called background task: $task");
try {
/// CALLBACK RUNS BUT AUDIO DOES NOT PLAY HERE
await player.setAsset('assets/sample.mp3');
await player.play();
} catch (e) {
developer.log(e.toString());
throw Exception(e);
}
return Future.value(true);
});
}
void main() {
WidgetsFlutterBinding.ensureInitialized();
Workmanager().initialize(callbackDispatcher);
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
bool _taskRegistered = false;
@override
void initState() {
WidgetsBinding.instance.addObserver(this);
super.initState();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed ||
state == AppLifecycleState.inactive) {
_registerTask();
}
}
/// etc.