When I launch the application, then everything is fine. The user interface works as expected. But when I close the application and remove it from the phone memory, the service stops and it can no longer be started. When you restart the application, a new window with the interface opens, and the first one does not disappear. Only the second window works. A lot of interface windows can be created this way. What could be the problem? And how to close the window when the application is removed from memory?
void main() async {
WidgetsFlutterBinding.ensureInitialized();
MobileAds.instance.initialize();
await setupServiceLocator();
runApp(const MyApp());
}
import 'package:audio_service/audio_service.dart';
import 'package:get_it/get_it.dart';
import 'audio_player_handler.dart';
import 'data.dart';
import 'home.dart';
GetIt getIt = GetIt.instance;
Future<void> setupServiceLocator() async {
// services
if(!getIt.isRegistered<AudioHandler>()) {
getIt.registerSingleton<AudioHandler>(await initAudioService());
}
}
import 'package:audio_service/audio_service.dart';
import 'package:just_audio/just_audio.dart';
final audioPlayer = AudioPlayer();
Future<AudioHandler> initAudioService() async {
return await AudioService.init(
builder: () => AudioPlayerHandler(),
config: AudioServiceConfig(
androidNotificationChannelId: 'top.musicplus.audio',
androidNotificationChannelName: 'Audio Service Demo',
androidNotificationOngoing: true,
androidStopForegroundOnPause: true,
androidNotificationIcon: 'drawable/fone_start'
),
);
}
class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
/// Initialise our audio handler.
AudioPlayerHandler() {
audioPlayer.playbackEventStream.map(_transformEvent).pipe(playbackState);
}
@override
Future<void> updateMediaItem(MediaItem mediaItem) async {
this.mediaItem.add(mediaItem);
}
@override
Future<void> play() => audioPlayer.play();
@override
Future<void> pause() => audioPlayer.pause();
@override
Future<void> stop() => audioPlayer.stop();
@override
PlaybackState _transformEvent(PlaybackEvent event) {
return PlaybackState(
controls: [
//MediaControl.rewind,
audioPlayer.playing ? MediaControl.pause : MediaControl.play,
//MediaControl.stop,
//MediaControl.fastForward,
],
systemActions: const {
MediaAction.seek,
MediaAction.seekForward,
MediaAction.seekBackward,
},
// androidCompactActionIndices: const [0, 1, 3],
androidCompactActionIndices: const [0],
processingState: const {
ProcessingState.idle: AudioProcessingState.idle,
ProcessingState.loading: AudioProcessingState.loading,
ProcessingState.buffering: AudioProcessingState.buffering,
ProcessingState.ready: AudioProcessingState.ready,
ProcessingState.completed: AudioProcessingState.completed,
}
[audioPlayer.processingState]!,
playing: audioPlayer.playing,
updatePosition: audioPlayer.position,
bufferedPosition: audioPlayer.bufferedPosition,
speed: audioPlayer.speed,
queueIndex: event.currentIndex,
);
}
}


