You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Expo推送通知:如何将应用图标角标数加1

Expo推送通知角标增量更新方案

一、客户端监听通知并更新角标

如果不想依赖服务端存储计数,可直接在客户端监听推送通知到达事件,实时累加角标数:

  1. 确保项目已引入expo-notifications模块(Expo项目默认包含)
  2. 添加如下逻辑:
import * as Notifications from 'expo-notifications';

// 首次启动时申请通知权限
async function setupNotificationPermissions() {
  const { status } = await Notifications.requestPermissionsAsync();
  if (status !== 'granted') {
    alert('需开启通知权限才能更新应用角标');
    return;
  }
}

// 监听通知到达事件,更新角标
Notifications.addNotificationReceivedListener(async () => {
  const currentCount = await Notifications.getBadgeCountAsync();
  await Notifications.setBadgeCountAsync(currentCount + 1);
});

注意:Android部分品牌设备不支持应用角标,需额外适配;iOS后台状态下该监听也会正常触发。

二、服务端实现角标增量更新

如果需要跨设备同步角标计数,或确保数值准确,建议由服务端统一维护用户的角标数值:

  1. 服务端新增存储(比如数据库表),记录每个用户的当前角标数(字段如user_id、badge_count)
  2. 发送推送前先查询用户当前计数,累加后再推送,同时更新数据库:
// 示例:Node.js + MySQL 实现
// 1. 查询用户当前角标数
async function getUserBadge(userId) {
  const [rows] = await db.query('SELECT badge_count FROM user_badges WHERE user_id = ?', [userId]);
  return rows.length ? rows[0].badge_count : 0;
}

// 2. 更新用户角标数到数据库
async function updateUserBadge(userId, newCount) {
  await db.query(
    'INSERT INTO user_badges (user_id, badge_count) VALUES (?, ?) ON DUPLICATE KEY UPDATE badge_count = ?',
    [userId, newCount, newCount]
  );
}

// 3. 发送推送通知
async function sendNotification(userId, pushToken, person, messages) {
  const currentBadge = await getUserBadge(userId);
  const newBadge = currentBadge + 1;

  // 更新数据库计数
  await updateUserBadge(userId, newBadge);

  // 调用Expo推送API
  await fetch('https://exp.host/--/api/v2/push/send', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      to: pushToken,
      title: `${person.username} size mesaj gönderdi`,
      body: `${messages[0].text}`,
      badge: newBadge,
      "content-available": 1,
      data: { url: "myApp://ChatList", type: "chat" },
    }),
  });
}

补充:当用户手动清除角标或打开应用后,需调用服务端接口重置计数,避免数值偏差。

内容的提问来源于stack exchange,提问作者İbrahim Bilgic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 06:30:37