Установка пользовательской мелодии звонка на переднем плане работает нормально, но на заднем плане не работаетAndroid

Форум для тех, кто программирует под Android
Ответить Пред. темаСлед. тема
Anonymous
 Установка пользовательской мелодии звонка на переднем плане работает нормально, но на заднем плане не работает

Сообщение Anonymous »

Привет, я пытаюсь реализовать собственную мелодию звонка, когда получаю уведомление на переднем плане, работает нормально, мелодия звонка воспроизводится и останавливается нормально, но когда приложение находится в фоновом режиме, мелодия звонка, но невозможно остановить его, я обнаружил, что handleBackgroundMessage создает новый экземпляр и в MyApp имеет разные экземпляры объектов и
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
NotificationHandler().onSelectNotification(json.encode(message.data));
});

этот метод вызывается из Myapp, поэтому он имеет другой экземпляр, может ли кто-нибудь подсказать, что я делаю неправильно, мой код ниже
Future handleBackgroundMessage(RemoteMessage message) async {
if (Platform.isAndroid) {
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform);
} else if (Platform.isIOS) {
await Firebase.initializeApp();
}
final liveAstrologerController = Get.put(LiveAstrologerController());
final walletController = Get.put(WalletController());
final chatController = Get.put(ChatController);
final callController = Get.put(CallController());
final reportController = Get.put(ReportController());
if (message.notification!.title == "For Live Streaming Chat") {
Future.delayed(const Duration(milliseconds: 500)).then((value) async {
await localNotifications.cancelAll();
});
String sessionType = message.data["sessionType"];
if (sessionType == "start") {
String? liveChatUserName2 = message.data['liveChatSUserName'];
if (liveChatUserName2 != null) {
liveAstrologerController.liveChatUserName = liveChatUserName2;
liveAstrologerController.update();
}
String chatId = message.data["chatId"];
liveAstrologerController.isUserJoinAsChat = true;
liveAstrologerController.update();
liveAstrologerController.chatId = chatId;
int waitListId = int.parse(message.data["waitListId"].toString());
String time = liveAstrologerController.waitList
.where((element) => element.id == waitListId)
.first
.time;
liveAstrologerController.endTime = DateTime.now().millisecondsSinceEpoch +
1000 * int.parse(time.toString());
liveAstrologerController.update();
} else {}
} else if (message.notification!.title ==
"For timer and session start for live") {
liveAstrologerController.update();
} else if (message.notification!.title == "Start simple chat timer") {
} else {
try {
if (message.data.isNotEmpty) {
var messageData = json.decode((message.data['body']));

if (messageData['notificationType'] != null) {
if (messageData['notificationType'] == 7) {
// get wallet api call
await walletController.getAmountList();
} else if (messageData['notificationType'] == 8) {
chatController.startRingTone();
//AlarmHandler.scheduleAlarm();
chatController.chatList.clear();
chatController.update();

await chatController.getChatList(false);
debugPrint('chat resp-> $messageData');
} else if (messageData['notificationType'] == 2) {
//in background
callController.startRingTone();

await callController.getCallList(false);
} else if (messageData['notificationType'] == 9) {
reportController.reportList.clear();
reportController.update();
await reportController.getReportList(false);
} else if (messageData['notificationType'] == 12 ||
messageData['notificationType'] == 11 ||
messageData['notificationType'] == 10) {
liveAstrologerController.isUserJoinWaitList = true;
liveAstrologerController.update();
}
}
}
} catch (e) {
debugPrint("Exception in _firebaseMessagingBackgroundHandler else $e");
}
}
}

и мое приложение
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await EasyLocalization.ensureInitialized();
await GetStorage.init();
await AndroidAlarmManager.initialize();

if (Platform.isAndroid) {
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform);
} else if (Platform.isIOS) {
await Firebase.initializeApp();
}

HttpOverrides.global = MyHttpOverrides();

runApp(
EasyLocalization(
supportedLocales: const [
Locale('en', 'US'),
],
path: 'assets/translations',
fallbackLocale: const Locale('en', 'US'),
startLocale: const Locale('en', 'US'),
child: const MyApp(),
),
);
}

class MyApp extends StatefulWidget {
const MyApp({super.key});

@override
State createState() => _MyAppState();
}

class _MyAppState extends State {
dynamic analytics;
final apiHelper = APIHelper();

dynamic observer;
final liveAstrologerController = Get.put(LiveAstrologerController());
final walletController = Get.put(WalletController());
final chatController = Get.put(ChatController());
final callController = Get.put(CallController());
final timerController = Get.put(TimerController());
final reportController = Get.put(ReportController());
final networkController = Get.put(NetworkController());

@override
void initState() {
super.initState();
log('chat hascode MyApp ${chatController.hashCode}');
log('call hascode MyApp ${callController.hashCode}');
inthandlerbackgroudn();

FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
if (message.notification!.title == "For Live Streaming Chat") {
String sessionType = message.data["sessionType"];
if (sessionType == "start") {
String? liveChatUserName2 = message.data['liveChatSUserName'];
if (liveChatUserName2 != null) {
liveAstrologerController.liveChatUserName = liveChatUserName2;
liveAstrologerController.update();
}
String chatId = message.data["chatId"];
liveAstrologerController.isUserJoinAsChat = true;
liveAstrologerController.update();
liveAstrologerController.chatId = chatId;
int waitListId = int.parse(message.data["waitListId"].toString());
String time = liveAstrologerController.waitList
.where((element) => element.id == waitListId)
.first
.time;
liveAstrologerController.endTime =
DateTime.now().millisecondsSinceEpoch +
1000 * int.parse(time.toString());
liveAstrologerController.update();
} else {
if (liveAstrologerController.isOpenPersonalChatDialog) {
Get.back(); //if chat dialog opended
liveAstrologerController.isOpenPersonalChatDialog = false;
}
liveAstrologerController.isUserJoinAsChat = false;
liveAstrologerController.chatId = null;
liveAstrologerController.update();
}
} else if (message.notification!.title ==
"For timer and session start for live") {
int waitListId = int.parse(message.data["waitListId"].toString());
liveAstrologerController.joinedUserName =
message.data["name"] ?? "User";
liveAstrologerController.joinedUserProfile =
message.data["profile"] ?? "";
String time = liveAstrologerController.waitList
.where((element) => element.id == waitListId)
.first
.time;
liveAstrologerController.endTime =
DateTime.now().millisecondsSinceEpoch +
1000 * int.parse(time.toString());
liveAstrologerController.update();
} else if (message.notification!.title == "Start simple chat timer") {
chatController.newIsStartTimer = true;
chatController.update();

timerController.endTime =
DateTime.now().millisecondsSinceEpoch + 1000 * 300;
timerController.update();
} else if (message.notification!.title == "End chat from customer") {
log('isInChatScreen ${chatController.isInChatScreen}');

if (chatController.isInChatScreen) {
chatController.updateChatScreen(false);
apiHelper.setAstrologerOnOffBusyline("Online");
chatController.update();

// Get.back();
} else {
log('do nothing chat dismiss');
}
} else if (message.notification!.title ==
"Reject call request from astrologer") {
print('user Rejected call request:-');
callController.isRejectCall = true;
callController.update();
callController.rejectDialog();
} else {
try {
if (message.data.isNotEmpty) {
var messageData = json.decode((message.data['body']));

log('noti body $messageData');
if (messageData['notificationType'] != null) {
if (messageData['notificationType'] == 7) {
// get wallet api call
await walletController.getAmountList();
NotificationHandler().foregroundNotification(message);
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true, badge: true, sound: true);
} else if (messageData['notificationType'] == 8) {
log('inside foreground noti type 8');
chatController.startRingTone();
chatController.chatList.clear();
chatController.update();
await chatController.getChatList(false);
NotificationHandler().foregroundNotification(message);
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true, badge: true, sound: true);

//SHOW CHAT DIALOG
} else if (messageData['notificationType'] == 2) {
callController.startRingTone();

log('iniside noti type 2');
callController.callList.clear();
callController.update();
await callController.getCallList(false);
NotificationHandler().foregroundNotification(message);
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true, badge: true, sound: true);
} else if (messageData['notificationType'] == 9) {
reportController.reportList.clear();
reportController.update();
await reportController.getReportList(false);
NotificationHandler().foregroundNotification(message);
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true, badge: true, sound: true);
} else if (messageData['notificationType'] == 12 ||
messageData['notificationType'] == 11 ||
messageData['notificationType'] == 10) {
liveAstrologerController.isUserJoinWaitList = true;
liveAstrologerController.update();
NotificationHandler().foregroundNotification(message);
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true, badge: true, sound: true);
} else {
NotificationHandler().foregroundNotification(message);
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true, badge: true, sound: true);
}

NotificationHandler().foregroundNotification(message);
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true, badge: true, sound: true);
} else {
NotificationHandler().foregroundNotification(message);
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true, badge: true, sound: true);
}
} else {
NotificationHandler().foregroundNotification(message);
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true, badge: true, sound: true);
}
} catch (e) {
NotificationHandler().foregroundNotification(message);
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true, badge: true, sound: true);
}
}
});
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
NotificationHandler().onSelectNotification(json.encode(message.data));
});
}
SplashController splashController = Get.put(SplashController());
@override
Widget build(BuildContext context) {
return GetBuilder(builder: (s) {
return Sizer(
builder: (context, orientation, deviceType) => GetMaterialApp(
debugShowCheckedModeBanner: false,
navigatorKey: Get.key,
enableLog: true,
theme: Themes.light,
darkTheme: Themes.dark,
themeMode: ThemeService().theme,
locale: context.locale,
localizationsDelegates: [
...context.localizationDelegates,
FallbackLocalizationDelegate()
],
supportedLocales: context.supportedLocales,
initialBinding: NetworkBinding(),
title: global.appName,
initialRoute: "SplashScreen",
home: SplashScreen(
a: analytics,
o: observer,
),

),
);
});
}

void inthandlerbackgroudn() async {
FirebaseMessaging messaging = FirebaseMessaging.instance;
FirebaseMessaging.onBackgroundMessage(handleBackgroundMessage);
await messaging.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: false,
);
}
}

и мой класс NotificaitonHandler —
class NotificationHandler {
final localNotifications = FlutterLocalNotificationsPlugin();
WalletController walletController = Get.put(WalletController());
ReportController reportController = Get.put(ReportController());
HomeController homecontroller = Get.put(HomeController());
SignupController signupController = Get.put(SignupController());
ChatController chatController = Get.find();
CallController callController = Get.find();

Future onSelectNotification(String payload) async {
Map messageData;
try {
messageData = json.decode(payload);
Map body;
body = jsonDecode(messageData['body']);
if (body["notificationType"] == 7) {
await walletController.getAmountList();
Get.to(() => WalletScreen());
} else if (body["notificationType"] == 8) {
chatController.stopRingtone();
Get.find().homeTabIndex = 0;
Get.find().update();
Get.to(() => const HomeScreen());
} else if (body["notificationType"] == 2) {
callController.stopRingtone();
debugPrint('list length ${callController.callList.length}');
callController.callList
.removeWhere((call) => call.callId == body['callId']);
callController.update();
if (body['call_type'].toString() == '10') {
callController.acceptCallRequest(
body['callId'],
body['profile'],
body['name'],
body['id'],
body['fcmToken'],
body['call_duration']);
} else if (body['call_type'].toString() == '11') {
callController.acceptVideoCallRequest(
body['callId'],
body['profile'],
body['name'],
body['id'],
body['fcmToken'],
body['call_duration']);
}
Get.find().homeTabIndex = 2; //pageview index
Get.find().isSelectedBottomIcon = 1; // bottom bar index
Get.find().update();
} else if (body["notificationType"] == 9) {
} else if (body["notificationType"] == 13) {
if (Get.find().notificationHandlingremoteUID != 0) {
global.showToast(message: 'You are already live, end call first');
} else {}
}
} catch (e) {
debugPrint(
'Exception in onSelectNotification main.dart:- ${e.toString()}',
);
}


Future foregroundNotification(RemoteMessage payload) async {
final DarwinInitializationSettings initializationSettingsDarwin =
DarwinInitializationSettings(
defaultPresentBadge: true,
requestSoundPermission: true,
requestBadgePermission: true,
defaultPresentSound: true,
onDidReceiveLocalNotification: (id, title, body, payload) async {
debugPrint("object notification call");
return;
},
);
AndroidInitializationSettings android =
const AndroidInitializationSettings('@mipmap/ic_launcher');
final InitializationSettings initialSetting = InitializationSettings(
android: android, iOS: initializationSettingsDarwin);
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
flutterLocalNotificationsPlugin.initialize(initialSetting,
onDidReceiveNotificationResponse: (_) {
NotificationHandler().onSelectNotification(json.encode(payload.data));
});
AndroidNotificationChannel channel = const AndroidNotificationChannel(
' local notifications',
'High Importance Notifications for ',
importance: Importance.high,
);

AndroidNotificationDetails androidDetails = AndroidNotificationDetails(
channel.id,
channel.name,
importance: Importance.max,
priority: Priority.high,
icon: "@mipmap/ic_launcher",
playSound: false,
styleInformation: const BigTextStyleInformation(''),
);
const DarwinNotificationDetails iOSDetails = DarwinNotificationDetails();
NotificationDetails platformChannelSpecifics =
NotificationDetails(android: androidDetails, iOS: iOSDetails);
global.sp = await SharedPreferences.getInstance();
if (global.sp!.getString("currentUser") != null) {
await flutterLocalNotificationsPlugin.show(
0,
payload.notification!.title,
payload.notification!.body,
platformChannelSpecifics,
payload: json.encode(payload.data.toString()),
);
}

}
}
Я получаю два разных hascode экземпляра чат-контроллера в своем приложении, и в выбранном уведомлении есть
[log] chat hascode MyApp 445182886
[log] chat hascode bghandler 668612596
[log] chat hascode NotificationHandler 445182886



Подробнее здесь: https://stackoverflow.com/questions/783 ... und-not-wo
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Android»