I am trying to create a basic alarm app which plays a sound at the given time. For this, I am using the android_alarm_manager plugin. To play the sound, I am using the flutter_ringtone_player plugin
main(List<String> args) async {
WidgetsFlutterBinding.ensureInitialized();
await AndroidAlarmManager.initialize();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
...
home: HomeScreen(),
),
);
}
}
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
@override
void initState() {
AndroidAlarmManager.initialize();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
...
floatingActionButton: FloatingActionButton(
child: Icon(Icons.alarm),
onPressed: () async {
await AndroidAlarmManager.oneShotAt(
DateTime.now().add(Duration(seconds: 5)),
10,
_fireAlarm,
);
},
),
);
}
}
void _fireAlarm() {
FlutterRingtonePlayer.play(
android: AndroidSounds.notification,
ios: IosSounds.glass,
looping: true, // Android only - API >= 28
volume: 0.1, // Android only - API >= 28
asAlarm: false, // Android only - all APIs
);
print('Alarm fired!');
}
The application runs as intended when it is in foreground. However, when the floatingActionButton
is tapped and the app is closed, the app crashes in the background.
I am using flutter version 2.0.6 and the API version of the emulator is 29, which I believe comes with Flutter Android Embedding V2 which means no additional configuration is required according to the documentation (at the bottom).
I have tried looking at resources on the web but I did not have much luck.