flutter_background_service 0.0.1+13 flutter_background_service: ^0.0.1+13 copied to clipboard
A flutter plugin for executing dart code continously even application closed.
import 'dart:async';
import 'package:audioplayer/audioplayer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_background_service/flutter_background_service.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
FlutterBackgroundService.initialize(onStart);
runApp(MyApp());
}
void onStart() {
WidgetsFlutterBinding.ensureInitialized();
final service = FlutterBackgroundService();
final audioPlayer = AudioPlayer();
String url =
"https://www.mediacollege.com/downloads/sound-effects/nature/forest/rainforest-ambient.mp3";
audioPlayer.onPlayerStateChanged.listen((event) {
if (event == AudioPlayerState.COMPLETED) {
audioPlayer.play(url);
}
});
audioPlayer.play(url);
service.onDataReceived.listen((event) {
print(event);
});
Timer.periodic(Duration(seconds: 1), (timer) {
service.setNotificationInfo(
title: "My App Service",
content: "Updated at ${DateTime.now()}",
);
service.sendData(
{"current_date": DateTime.now().toIso8601String()},
);
});
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Service App'),
),
body: StreamBuilder<Map<String, dynamic>>(
stream: FlutterBackgroundService().onDataReceived,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
final data = snapshot.data;
DateTime date = DateTime.tryParse(data["current_date"]);
return Text(date.toString());
},
),
floatingActionButton: FloatingActionButton(
onPressed: () {
FlutterBackgroundService().sendData({
"hello": "world",
});
},
child: Icon(Icons.play_arrow),
),
),
);
}
}