Ионные/конденсаторные push-уведомления не работают на переднем планеAndroid

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Ионные/конденсаторные push-уведомления не работают на переднем плане

Сообщение Anonymous »

Я разрабатываю мобильное приложение, использующее Ionic + Capacitor с Firebase Cloud Messaging (FCM) для push-уведомлений. Уведомления отлично работают в фоновом режиме и в состояниях «выключено» на Android, но на переднем плане они работают неправильно.
В фоновом/выключенном состоянии: уведомления приходят, отображаются, и нажатие на них запускает правильное событие (pushNotificationActionPerformed) для глубокой связи с приложением.
В состоянии переднего плана:
Событие pushNotificationReceived срабатывает, как и ожидалось.
Однако нажатие уведомление не запускает pushNotificationActionPerformed, поскольку уведомление не отображается изначально.
Я реализовал временное решение для отображения уведомлений через Toast-сообщения на переднем плане, но это не идеально, поскольку оно не копирует встроенное поведение уведомлений.
Конфигурация конденсатора (capacitor.config.ts)
presentationOptions: ["badge", "sound", "alert"]
}

Код внешнего интерфейса (NotificationService)
console.log('🚨 Notification received (Foreground):', notification);

const { title, body } = notification;
const data = notification.data || {};

await this.presentToastNotification(
title || 'New Notification',
body || 'You have a new message',
data?.conversacionId
);

console.log('✅ Notification shown as Toast in Foreground.');
});

Уведомление о маршруте Backend nodejs
notificacionRuta.post('/crear-notificacion', async (req: Request, res: Response) => {
try {
const { receptorId, mensaje, titulo, conversacionId } = req.body;

if (!titulo || !mensaje || !receptorId || !conversacionId) {
return res.status(400).json({ error: 'El título, mensaje, receptorId y conversacionId son obligatorios.' });
}

// Crear y guardar la notificación
const notificacion = new Notificacion({
usuarioDestino: receptorId,
mensaje,
titulo,
fecha: new Date(),
tipo: 'mensaje',
leido: false,
});

const savedNotificacion = await notificacion.save();
console.log('✅ Notificación guardada:', savedNotificacion);

// Obtener los tokens del usuario
const receptor = await Usuario.findById(receptorId);
if (!receptor || !receptor.deviceTokens || receptor.deviceTokens.length === 0) {
return res.status(404).json({ error: 'Token del dispositivo no encontrado' });
}

// Enviar notificación push
await sendPushNotificationMultiple(receptor.deviceTokens, mensaje, titulo, receptorId, conversacionId);

res.status(201).json(savedNotificacion);
} catch (error) {
console.error('❌ Error al crear la notificación:', error);
logger.error('Error al crear notificación', { error: JSON.stringify(error, null, 2) });
res.status(500).json({ error: 'Error al crear notificación', details: error });
}
});

/**
* Función para enviar notificación push a múltiples dispositivos
*/
async function sendPushNotificationMultiple(
tokens: string[],
mensaje: string,
titulo: string,
receptorId: string,
conversacionId: string
) {
try {
if (!tokens || tokens.length === 0) {
throw new Error('No hay tokens de dispositivos válidos para enviar la notificación.');
}

const payload = {
notification: {
title: titulo,
body: mensaje,
},
data: {
title: titulo,
body: mensaje,
type: 'chat',
conversacionId: conversacionId,
receptorId: receptorId,
},
android: {
priority: 'high' as const,
notification: {
channelId: 'default',
},
},
apns: {
payload: {
aps: {
contentAvailable: true, // Para notificaciones en primer plano
alert: {
title: titulo,
body: mensaje,
},
},
},
headers: {
'apns-priority': '10',
},
},
};

const response = await admin.messaging().sendEachForMulticast({
tokens,
notification: payload.notification,
data: payload.data,
android: payload.android,
apns: payload.apns,
});

console.log('✅ Notificaciones enviadas:', response);

const invalidTokens: string[] = [];

response.responses.forEach((resp, idx) => {
if (!resp.success) {
console.error(
`❌ Error en el token ${tokens[idx]}: ${resp.error?.message || 'Error desconocido'}`
);

if (resp.error?.code === 'messaging/registration-token-not-registered') {
invalidTokens.push(tokens[idx]);
}
}
});

if (invalidTokens.length > 0) {
await Usuario.updateOne(
{ _id: receptorId },
{ $pull: { deviceTokens: { $in: invalidTokens } } }
);
console.log('✅ Tokens inválidos eliminados:', invalidTokens);
}
} catch (error) {
console.error('❌ Error al enviar la notificación push múltiple:', error);
throw error;
}
}


Подробнее здесь: https://stackoverflow.com/questions/793 ... foreground
Ответить

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

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

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

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

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