80 lines
2.6 KiB
Java
80 lines
2.6 KiB
Java
package com.example.livestreaming;
|
||
|
||
import android.content.Context;
|
||
import android.content.SharedPreferences;
|
||
|
||
import com.google.android.material.badge.BadgeDrawable;
|
||
import com.google.android.material.bottomnavigation.BottomNavigationView;
|
||
|
||
public class UnreadMessageManager {
|
||
|
||
private static final String PREFS_NAME = "unread_messages";
|
||
private static final String KEY_UNREAD_COUNT = "unread_count";
|
||
|
||
/**
|
||
* 获取总未读消息数量
|
||
* TODO: 接入后端接口 - 从后端获取未读消息总数
|
||
* 接口路径: GET /api/messages/unread/count
|
||
* 请求参数: 无(从token中获取userId)
|
||
* 返回数据格式: ApiResponse<{unreadCount: number}>
|
||
* 建议:在应用启动时和进入后台后重新进入时调用此接口更新未读数量
|
||
*/
|
||
public static int getUnreadCount(Context context) {
|
||
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
|
||
return prefs.getInt(KEY_UNREAD_COUNT, 0);
|
||
}
|
||
|
||
/**
|
||
* 设置总未读消息数量
|
||
*/
|
||
public static void setUnreadCount(Context context, int count) {
|
||
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
|
||
prefs.edit().putInt(KEY_UNREAD_COUNT, Math.max(0, count)).apply();
|
||
}
|
||
|
||
/**
|
||
* 增加未读消息数量
|
||
*/
|
||
public static void incrementUnreadCount(Context context, int increment) {
|
||
int current = getUnreadCount(context);
|
||
setUnreadCount(context, current + increment);
|
||
}
|
||
|
||
/**
|
||
* 减少未读消息数量
|
||
*/
|
||
public static void decrementUnreadCount(Context context, int decrement) {
|
||
int current = getUnreadCount(context);
|
||
setUnreadCount(context, Math.max(0, current - decrement));
|
||
}
|
||
|
||
/**
|
||
* 更新底部导航栏的消息徽章
|
||
*/
|
||
public static void updateBadge(BottomNavigationView bottomNav) {
|
||
if (bottomNav == null) return;
|
||
|
||
Context context = bottomNav.getContext();
|
||
int unreadCount = getUnreadCount(context);
|
||
|
||
BadgeDrawable badge = bottomNav.getOrCreateBadge(R.id.nav_messages);
|
||
|
||
if (unreadCount > 0) {
|
||
badge.setVisible(true);
|
||
badge.setNumber(unreadCount);
|
||
// BadgeDrawable 会自动处理超过 99 的情况,显示 "99+"
|
||
} else {
|
||
badge.setVisible(false);
|
||
badge.clearNumber();
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 清除未读消息数量(当用户进入消息页面时)
|
||
*/
|
||
public static void clearUnreadCount(Context context) {
|
||
setUnreadCount(context, 0);
|
||
}
|
||
}
|
||
|