diff --git a/example/lib/main.dart b/example/lib/main.dart index e82580ee..0fed4c63 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -1,7 +1,7 @@ import 'package:flutter/material.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; -Future _handleBackgroundNotification( +Future _handleAndroidNotification( Map notification, ) async { final notificationData = @@ -30,7 +30,7 @@ void main() async { final client = Client( 's2dxdhpxd94g', logLevel: Level.INFO, - customAndroidNotificationHandler: _handleBackgroundNotification, + androidNotificationHandler: _handleAndroidNotification, ); await client.setUser( diff --git a/lib/src/stream_chat.dart b/lib/src/stream_chat.dart index debd67ce..842a0699 100644 --- a/lib/src/stream_chat.dart +++ b/lib/src/stream_chat.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:io'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; @@ -61,6 +62,7 @@ class StreamChat extends StatefulWidget { class StreamChatState extends State with WidgetsBindingObserver { Client get client => widget.client; final GlobalKey _navigatorKey = GlobalKey(); + Timer _disconnectTimer; @override Widget build(BuildContext context) { @@ -185,14 +187,35 @@ class StreamChatState extends State with WidgetsBindingObserver { WidgetsBinding.instance.addObserver(this); } + StreamSubscription _newMessageSubscription; + @override void didChangeAppLifecycleState(AppLifecycleState state) { if (state == AppLifecycleState.paused) { - client.disconnect(); + if (Platform.isAndroid) { + _newMessageSubscription = + client.on(EventType.messageNew).listen((event) { + client.androidNotificationHandler({ + 'data': { + 'message_id': event.message.id, + }, + }); + }); + _disconnectTimer = Timer(Duration(minutes: 1), () { + client.disconnect(); + }); + } else { + client.disconnect(); + } } else if (state == AppLifecycleState.resumed) { - if (client.wsConnectionStatus.value == ConnectionStatus.disconnected) { - NotificationService.handleIosMessageQueue(client); - client.connect(); + _newMessageSubscription?.cancel(); + if (_disconnectTimer?.isActive == true) { + _disconnectTimer.cancel(); + } else { + if (client.wsConnectionStatus.value == ConnectionStatus.disconnected) { + NotificationService.handleIosMessageQueue(client); + client.connect(); + } } } }