You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I have implemented all methods of firebase messaging onmessage, onmessageopened, getintial, backgroundmessge,
I am trying to make redirection when app is in termination mode then getbackground message handle is called and based on this screen is redireceted and then getintialmessage is callled in ios and
In Android in temrination mode notification click redirection is done on background message handler and then started didlaunchnotificaions of flutter local notificaiton so could not manage for android and ios and redirection is not done proper ,
in ios redirection is done but got pop from that screen to main screen, and android getting some navigator issue for redirection
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
-
Hello ,
I have implemented all methods of firebase messaging onmessage, onmessageopened, getintial, backgroundmessge,
I am trying to make redirection when app is in termination mode then getbackground message handle is called and based on this screen is redireceted and then getintialmessage is callled in ios and
In Android in temrination mode notification click redirection is done on background message handler and then started didlaunchnotificaions of flutter local notificaiton so could not manage for android and ios and redirection is not done proper ,
in ios redirection is done but got pop from that screen to main screen, and android getting some navigator issue for redirection
Please help me in it.
import 'dart:convert';
import 'dart:io';
import 'dart:math';
// import 'package:connectycube_flutter_call_kit/connectycube_flutter_call_kit.dart';
// import 'package:connectycube_sdk/connectycube_core.dart';
// import 'package:connectycube_sdk/connectycube_sdk.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:human_quest/module/quick_blox/quick_blox_callmanager.dart';
import 'package:human_quest/module/quick_blox/quick_blox_chatmanager.dart';
// import 'package:flutter_voip_push_notification/flutter_voip_push_notification.dart';
// import 'package:human_quest/module/call/call_manager.dart';
// import 'package:human_quest/module/chat/view/configs.dart' as config;
import 'package:human_quest/utils/common_imports.dart';
import 'package:human_quest/utils/navigator_key.dart';
import 'package:quickblox_sdk/models/qb_subscription.dart';
import 'package:quickblox_sdk/push/constants.dart';
import 'package:quickblox_sdk/quickblox_sdk.dart';
// import 'package:platform_device_id/platform_device_id.dart';
// import 'package:universal_io/io.dart';
class PushNotificationsManager {
static const TAG = "PushNotificationsManager";
static int _semaphore = 0;
static final PushNotificationsManager _instance =
PushNotificationsManager._internal();
late FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
PushNotificationsManager._internal() {
Firebase.initializeApp();
flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
}
// final FlutterVoipPushNotification _voipPush = FlutterVoipPushNotification();
BuildContext? applicationContext;
static PushNotificationsManager get instance => _instance;
Future Function(String? payload)? onNotificationClicked;
init() async {
FirebaseMessaging firebaseMessaging = FirebaseMessaging.instance;
PrintLog.printLog(TAG + "init()");
await firebaseMessaging.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: true,
);
/*
String? token;
if (Platform.isAndroid) {
firebaseMessaging.getToken().then((token) {
log('[getToken] token: $token', TAG);
subscribe(token);
}).catchError((onError) {
log('[getToken] onError: $onError', TAG);
});
} else if (Platform.isIOS) {
// token = await firebaseMessaging.getAPNSToken();
*/
firebaseMessaging.onTokenRefresh.listen((newToken) async {
PrintLog.printLog('firebaseMessaging onTokenRefresh ===');
SharedPref.saveValueToPrefs(
EnumSharedPrefsDataType.string_data_type, SharedPref.token, newToken);
// _createPushSubscription(deviceToken: newToken);
// subscribe(newToken);
});
}
/*
_initIosVoIP() async {
await _voipPush.requestNotificationPermissions();
_voipPush.configure(onMessage: onMessage, onResume: onResume);
}
subscribe(String? token) async {
PrintLog.printLog('[subscribe] token: $token');
}
unsubscribe() {
int subscriptionId = SharedPref.getSubscriptionId();
if (subscriptionId != 0) {
deleteSubscription(subscriptionId).then((voidResult) {
FirebaseMessaging.instance.deleteToken();
SharedPref.saveSubscriptionId(0);
});
}
}
*/
Future onDidReceiveLocalNotification(
int id, String? title, String? body, String? payload) {
PrintLog.printLog(
'[onDidReceiveLocalNotification] id: $id , title: $title, body: $body, payload: $payload' +
PushNotificationsManager.TAG);
return Future.value();
}
Future onSelectNotification(String? payload) {
PrintLog.printLog('[onSelectNotification] payload: $payload' +
PushNotificationsManager.TAG);
if (onNotificationClicked != null) {
onNotificationClicked!.call(payload);
}
return Future.value();
}
Future _createPushSubscription({required String deviceToken}) async {
try {
if (Platform.isAndroid) {
List<QBSubscription?> subscriptions =
await QB.subscriptions.create(deviceToken, QBPushChannelNames.GCM);
int subscriptionsId = subscriptions[0]?.id ?? 0;
SharedPref.saveValueToPrefs(EnumSharedPrefsDataType.int_data_type,
SharedPref.androidSubscriptionId, subscriptionsId);
PrintLog.printLog(
"Push was created with token: $deviceToken, subscription $subscriptionsId");
} else {
List<QBSubscription?> subscriptionsApns =
await QB.subscriptions.create(deviceToken, QBPushChannelNames.APNS);
int subscriptionsIdApns = subscriptionsApns[0]?.id ?? 0;
SharedPref.saveValueToPrefs(EnumSharedPrefsDataType.int_data_type,
SharedPref.iosApnsSubscriptionId, subscriptionsIdApns);
PrintLog.printLog(
"Apns Push was created with token: $deviceToken, subscription $subscriptionsIdApns");
}
}
Future onMessage(bool isLocal, Map<String, dynamic> payload) {
PrintLog.printLog(
"[onMessage] received on foreground payload: $payload, isLocal=$isLocal" +
PushNotificationsManager.TAG);
// processCallNotification(payload);
return Future.value();
}
Future onResume(bool isLocal, Map<String, dynamic> payload) {
PrintLog.printLog(
"[onResume] received on background payload: $payload, isLocal=$isLocal" +
PushNotificationsManager.TAG);
return Future.value();
}
/*
processCallNotification(Map<String, dynamic> data) async {
log('[processCallNotification] message: $data', PushNotificationsManager.TAG);
String? signalType = data[PARAM_SIGNAL_TYPE];
String? sessionId = data[PARAM_SESSION_ID];
Set opponentsIds = (data[PARAM_CALL_OPPONENTS] as String)
.split(',')
.map((e) => int.parse(e))
.toSet();
if (signalType == SIGNAL_TYPE_START_CALL) {
CallManager.instance.seekerId = data[SEEKERID];
CallManager.instance.questionId = data[QUESTIONID];
CallManager.instance.providerId = data[PROVIDERID];
CallManager.instance.createdAt = data[CREATEDAT];
} else if (signalType == SIGNAL_TYPE_END_CALL) {
ConnectycubeFlutterCallKit.reportCallEnded(
sessionId: data[PARAM_SESSION_ID]);
} else if (signalType == SIGNAL_TYPE_REJECT_CALL) {
if (opponentsIds.length == 1) {
CallManager.instance.hungUp(true);
}
}
}
Future sendPushAboutRejectFromKilledState(
Map<String, dynamic> parameters,
int callerId,
) {
CubeSettings.instance.applicationId = config.APP_ID;
CubeSettings.instance.authorizationKey = config.AUTH_KEY;
CubeSettings.instance.authorizationSecret = config.AUTH_SECRET;
CubeSettings.instance.accountKey = config.ACCOUNT_ID;
CubeSettings.instance.onSessionRestore = () {
return createSession(SharedPref.getUser());
};
CreateEventParams params = CreateEventParams();
params.parameters = parameters;
params.parameters['message'] = "Reject call";
params.parameters[PARAM_SIGNAL_TYPE] = SIGNAL_TYPE_REJECT_CALL;
params.parameters[PARAM_IOS_VOIP] = 1;
params.notificationType = NotificationType.PUSH;
params.environment = CubeEnvironment
.DEVELOPMENT; // TODO for sample we use DEVELOPMENT environment
// bool isProduction = bool.fromEnvironment('dart.vm.product');
// params.environment =
// isProduction ? CubeEnvironment.PRODUCTION : CubeEnvironment.DEVELOPMENT;
params.usersIds = [callerId];
return createEvent(params.getEventForRequest());
}
*/
showNotification(RemoteMessage message) async {
PrintLog.printLog(
'[showNotification] message: $message' + PushNotificationsManager.TAG);
Map<String, dynamic> data = message.data;
PrintLog.printLog('data = ' + data.toString());
String clickAction = Platform.isAndroid ? data['click_action'] : "";
var customSound = AndroidNotificationDetails(
'',
'Chat',
sound: const RawResourceAndroidNotificationSound("caller"),
channelDescription: data['body'],
playSound: true,
importance: Importance.high,
priority: Priority.high,
showWhen: true,
color: Colors.green,
);
var normalSound = AndroidNotificationDetails(
'messages_channel_id',
'Chat',
sound: const RawResourceAndroidNotificationSound(""),
channelDescription: data['body'],
importance: Importance.high,
priority: Priority.high,
showWhen: true,
color: Colors.green,
);
AndroidNotificationDetails androidPlatformChannelSpecifics =
clickAction == "incoming_call_android" ? customSound : normalSound;
IOSNotificationDetails iOSNotificationDetails = const IOSNotificationDetails(
presentAlert: true,
presentBadge: true,
presentSound: true,
badgeNumber: 0,
);
NotificationDetails platformChannelSpecifics = NotificationDetails(
android: androidPlatformChannelSpecifics, iOS: iOSNotificationDetails);
FlutterLocalNotificationsPlugin().show(
Random().nextInt(100),
APPStrings.humanDotQuest,
data['message'].toString(), //data['body'].toString(),
platformChannelSpecifics,
payload: jsonEncode(data),
);
}
Future onBackgroundMessage(RemoteMessage message) async {
showToastBottom("onBackgroundMessage method");
await Firebase.initializeApp();
PrintLog.printLog('[onBackgroundMessage] message: ' + message.toString());
// ConnectycubeFlutterCallKit.onCallRejectedWhenTerminated = (
// sessionId,
// callType,
// callerId,
// callerName,
// opponentsIds,
// userInfo,
// ) {
// return sendPushAboutRejectFromKilledState({
// PARAM_CALL_TYPE: callType,
// PARAM_SESSION_ID: sessionId,
// PARAM_CALLER_ID: callerId,
// PARAM_CALLER_NAME: callerName,
// PARAM_CALL_OPPONENTS: opponentsIds.join(','),
// }, callerId);
// };
// ConnectycubeFlutterCallKit.initMessagesHandler();
if (message.data.isNotEmpty &&
message.data[PARAM_SIGNAL_TYPE] != null &&
message.data[PARAM_CALL_TYPE] != null) {
// processCallNotification(message.data);
} else if (message.data.isNotEmpty && message.data["message"] != null) {
if (Platform.isAndroid) {
showNotification(message);
}
} else {
message.data.putIfAbsent("message", () => "Notification");
// showNotification(message);
}
return Future.value();
}
dynamic onNotificationSelected(String? payload, BuildContext? context) {
PrintLog.printLog('[onSelectNotification] payload: $payload' +
PushNotificationsManager.TAG);
if (context == null) return Future.value();
showToastBottom("onNotificationSelected method");
PrintLog.printLog(
'[onSelectNotification] context != null' + PushNotificationsManager.TAG);
if (SharedPref.getBoolValue(SharedPref.isLogin)) {
if (payload != null && Platform.isIOS) {
Future.delayed(Duration(seconds: 2)).then((value) {
} else {
MyRouter.pushWithRouteName(context, loginRoute, null);
}
}
Beta Was this translation helpful? Give feedback.
All reactions