I do not receive custom push notifications when the application is closed #11697
Unanswered
experimentosconai
asked this question in
Q&A
Replies: 2 comments 1 reply
-
AndroidManifest.xml:
|
Beta Was this translation helpful? Give feedback.
0 replies
-
Did you tried it with debug, or release mode? I experienced the same when I started my app in Debug mode. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I have tried many times, so finally I want to come to you to find the solution to show the notification when the application is closed, as proof in mainpage.dart there is a Notifications icon, after clicking that icon it is notified in 5 seconds.
Within the logic of the icon there are 2 conditions, if the application status is active, the local notification is shown. Otherwise a push notification would be used using the function that comes in fcm_helper.dart.
Attached mainpage.dart, fcm_helper.dart, Manifest, Gradle, main.dart
mainpage.dart:
`import 'package:chatgpt_project/src/fcm/fcm_helper.dart';
//import 'package:chatgpt_project/src/notifications/fcm_schedule_notifications.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:chatgpt_project/src/authentication/auth_google.dart';
import 'package:chatgpt_project/src/routes/routes.dart';
import 'package:chatgpt_project/src/utils/constants.dart';
import 'package:chatgpt_project/src/views/calendario.dart';
import 'package:chatgpt_project/src/views/inicio.dart';
import 'package:chatgpt_project/src/views/mas.dart';
import 'package:chatgpt_project/src/views/mi_salud.dart';
import 'package:chatgpt_project/src/firestore/user_model.dart';
import 'package:chatgpt_project/src/notifications/schedule_notifications.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:timezone/timezone.dart' as tz;
class MainPage extends StatefulWidget {
final int initialIndex;
const MainPage({Key? key, this.initialIndex = 0}) : super(key: key);
@OverRide
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State with WidgetsBindingObserver {
final FirebaseAuth _auth = FirebaseAuth.instance;
UserModel? currentUser;
// 1. Inicialización del plugin de notificaciones locales
// final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
// FlutterLocalNotificationsPlugin();
int selectedIndex =
0; // Indice para controlar la navegación en la barra inferior
Future _signOut() async {
await signOutGoogle();
await _auth.signOut();
// ignore: use_build_context_synchronously
Navigator.pushNamedAndRemoveUntil(
context,
Routes.login,
(route) => false,
);
}
void _createNotificationChannel() {
const AndroidNotificationChannel channel = AndroidNotificationChannel(
'high_priority_channel', // id
'High Priority Notifications', // title
description: 'This channel is used for important notifications.',
importance: Importance.high,
playSound: true,
);
}
void _sendLocalNotification(tz.TZDateTime scheduledDate) async {
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails(
'high_priority_channel', // id
'High Priority Notifications', // title
importance: Importance.high,
priority: Priority.high,
showWhen: false,
playSound: true,
);
}
@OverRide
void initState() {
super.initState();
}
@OverRide
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@OverRide
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
// Aquí puedes manejar los cambios de estado si es necesario
}
void _requestNotificationPermissions() {
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
}
Future _getCurrentUser() async {
final firebaseUser = _auth.currentUser;
if (firebaseUser != null) {
final userDoc = await FirebaseFirestore.instance
.collection('users')
.doc(firebaseUser.uid)
.get();
setState(() {
currentUser = UserModel.fromFirestore(userDoc);
});
// Llamada a fetchMedicines
fetchMedicines(firebaseUser.uid);
}
}
@OverRide
Widget build(BuildContext context) {
final screens = [
if (currentUser != null)
InicioView(user: currentUser!), //aquí pasamos el usuario
const CalendarioView(),
if (currentUser != null)
MiSaludView(
user:
currentUser!), //user: currentUser! sirve para conectar con mi_salud.dart
const MasView()
];
}
}
`
fcm_helper.dart:
`Future getAccessToken() async {
try {
final client = http.Client();
final AccessCredentials credentials =
await obtainAccessCredentialsViaServiceAccount(_credentials,
['https://www.googleapis.com/auth/firebase.messaging'], client);
} catch (e) {
print("Error obteniendo el token de acceso: $e");
throw e;
}
}
Future sendPushNotification(
String token, String title, String body) async {
try {
const String sendUrl =
'https://fcm.googleapis.com/v1/projects/proyecto-chatgpt-84b99/messages:send';
final String accessToken = await getAccessToken();
} catch (e) {
print("Error sending the notification: $e");
throw e;
}
}`
AndroidManifest.xml:
`
build.gradle:
`def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
android {
compileSdkVersion 33
//compileSdkVersion flutter.compileSdkVersion
ndkVersion flutter.ndkVersion
}
flutter {
source '../..'
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.android.support:multidex:2.0.1'
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
implementation "androidx.window:window:1.0.0"
implementation "androidx.window:window-java:1.0.0"
}
main.dart:
import 'dart:ui';
import 'package:chatgpt_project/src/authentication/auth_google.dart';
//import 'package:chatgpt_project/src/fcm/fcm_helper.dart';
import 'package:chatgpt_project/src/notifications/schedule_notifications.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:chatgpt_project/src/routes/routes.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'firebase_options.dart';
//import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:intl/date_symbol_data_local.dart';
import 'package:provider/provider.dart';
import 'package:chatgpt_project/src/providers/chats_provider.dart';
import 'package:firebase_auth/firebase_auth.dart';
//import 'package:chatgpt_project/src/providers/models_provider.dart';
//import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_native_timezone/flutter_native_timezone.dart';
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
Future firebaseMessagingBackgroundHandler(RemoteMessage message) async {
print('Mensaje recibido en segundo plano: ${message.messageId}');
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails(
'high_priority_channel', // id
'High Priority Notifications', // title
importance: Importance.max,
priority: Priority.high,
showWhen: false,
);
const NotificationDetails platformChannelSpecifics =
NotificationDetails(android: androidPlatformChannelSpecifics);
await FlutterLocalNotificationsPlugin().show(
0, // ID de notificación
'Titulo Prueba',
'Esta es la descripcion Prueba',
platformChannelSpecifics,
payload: 'Default_Sound',
);
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
tz.initializeTimeZones();
final String timeZoneName = await FlutterNativeTimezone.getLocalTimezone();
tz.setLocalLocation(tz.getLocation(timeZoneName));
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
await initializeDateFormatting('es_ES', null);
_configureFirebaseListeners();
final CallbackHandle callback =
PluginUtilities.getCallbackHandle(callbackDispatcher)!;
final int callbackHandle = callback.toRawHandle();
final SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setInt('callback_handle', callbackHandle);
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => ChatProvider()),
],
child: const MyApp(),
),
);
}
Future updateTokenToFirestore(String token) async {
// Obtiene el userId del usuario autenticado
String? currentUserId = FirebaseAuth.instance.currentUser?.uid;
if (currentUserId != null) {
final docRef = _firestore.collection('users').doc(currentUserId);
final docSnapshot = await docRef.get();
}
}
void _configureFirebaseListeners() async {
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
// Obtener y manejar el token de FCM
_firebaseMessaging.getToken().then((String? token) {
assert(token != null);
print("Token de FCM: $token");
updateTokenToFirestore(token!);
});
// Escuchar cambios en el token
_firebaseMessaging.onTokenRefresh.listen((String token) {
print("Token de FCM actualizado: $token");
updateTokenToFirestore(token);
});
_firebaseMessaging.getInitialMessage().then((RemoteMessage? message) {
if (message != null) {
}
});
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
});
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
});
}
void fetchMedicinesFromBoot(List args) async {
// Aquí puedes invocar fetchMedicines con el userId que necesites.
String? userId =
await getUserId(); // Aquí deberías implementar la función getUserId si aún no lo has hecho.
if (userId != null) {
fetchMedicines(userId);
}
}
void callbackDispatcher() {
const MethodChannel _backgroundChannel =
MethodChannel('com.example.chatgpt_project/background_channel');
WidgetsFlutterBinding.ensureInitialized();
_backgroundChannel.setMethodCallHandler((MethodCall call) async {
if (call.method == 'fetchMedicinesFromBoot') {
fetchMedicinesFromBoot([]);
}
});
}
class MyApp extends StatelessWidget {
const MyApp({Key? key})
: super(
key:
key); //CON ANALYTICS: const MyApp({Key? key, required this.analytics}) : super(key: key);
@OverRide
Widget build(BuildContext context) {
return MaterialApp(
title: 'My App',
debugShowCheckedModeBanner: false,
initialRoute: Routes.loading,
routes: Routes.routes,
);
}
}`
flutter doctor -v
`[√] Flutter (Channel stable, 3.13.6, on Microsoft Windows [Versi¢n 10.0.19045.3448], locale es-PE)
• Flutter version 3.13.6 on channel stable at C:\src\flutter
• Upstream repository https://github.com/flutter/flutter.git
• Framework revision ead455963c (2 weeks ago), 2023-09-26 18:28:17 -0700
• Engine revision a794cf2681
• Dart version 3.1.3
• DevTools version 2.25.0
[√] Windows Version (Installed version of Windows is version 10 or higher)
[√] Android toolchain - develop for Android devices (Android SDK version 33.0.2)
• Android SDK at C:\Users\User\AppData\Local\Android\sdk
• Platform android-33-ext5, build-tools 33.0.2
• Java binary at: C:\Program Files\Android\Android Studio\jbr\bin\java
• Java version OpenJDK Runtime Environment (build 11.0.15+0-b2043.56-9505619)
• All Android licenses accepted.
[√] Chrome - develop for the web
• Chrome at C:\Program Files\Google\Chrome\Application\chrome.exe
[√] Visual Studio - develop Windows apps (Visual Studio Build Tools 2022 17.5.3)
• Visual Studio at C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools
• Visual Studio Build Tools 2022 version 17.5.33516.290
• Windows 10 SDK version 10.0.22621.0
[√] Android Studio (version 2022.1)
• Android Studio at C:\Program Files\Android\Android Studio
• Flutter plugin can be installed from:
https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build 11.0.15+0-b2043.56-9505619)
[√] VS Code (version 1.83.0)
• VS Code at C:\Users\User\AppData\Local\Programs\Microsoft VS Code
• Flutter extension version 3.74.0
[√] Connected device (4 available)
• sdk gphone64 x86 64 (mobile) • emulator-5554 • android-x64 • Android 13 (API 33) (emulator)
• Windows (desktop) • windows • windows-x64 • Microsoft Windows [Versi¢n 10.0.19045.3448]
• Chrome (web) • chrome • web-javascript • Google Chrome 117.0.5938.150
• Edge (web) • edge • web-javascript • Microsoft Edge 117.0.2045.60
[√] Network resources
• All expected network resources are available.
• No issues found!`
Beta Was this translation helpful? Give feedback.
All reactions