Android推送通知-显示发送时间而不是接收时间
创始人
2024-08-21 20:30:21
0

要在Android推送通知中显示发送时间而不是接收时间,可以通过设置通知的内容来实现。以下是一个示例代码,演示如何在Android中使用Firebase Cloud Messaging(FCM)发送通知并在通知中显示发送时间:

  1. 在Android项目的build.gradle文件中添加以下依赖项:
implementation 'com.google.firebase:firebase-messaging:22.0.0'
  1. 创建一个继承自FirebaseMessagingService的类,并实现onMessageReceived方法。在该方法中处理接收到的消息,并显示通知。
public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        // 获取消息的发送时间
        long sentTimeMillis = remoteMessage.getSentTime();

        // 格式化发送时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        String sentTime = sdf.format(new Date(sentTimeMillis));

        // 获取通知的标题和内容
        String title = remoteMessage.getNotification().getTitle();
        String body = remoteMessage.getNotification().getBody();

        // 创建通知的构建器
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "channel_id")
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle(title)
                .setContentText(body)
                .setAutoCancel(true)
                .setWhen(sentTimeMillis) // 设置通知的发送时间
                .setShowWhen(true); // 显示发送时间

        // 显示通知
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        notificationManager.notify(0, builder.build());
    }
}
  1. 在AndroidManifest.xml文件中注册MyFirebaseMessagingService类。

    
        
    

  1. 在应用的启动活动(例如MainActivity)中,确保已订阅Firebase消息服务。
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 订阅Firebase消息服务
        FirebaseMessaging.getInstance().subscribeToTopic("news");
    }
}

通过这个示例代码,你可以在Android推送通知中显示发送时间而不是接收时间。请注意,这里使用了Firebase Cloud Messaging(FCM)来发送通知,因此你需要设置Firebase项目并获取google-services.json文件。另外,你还需要在AndroidManifest.xml文件中添加通知的渠道信息,以及在通知中使用的图标和资源文件。

相关内容

热门资讯

玩家必看科普!川麻圈辅助工具(... 玩家必看科普!川麻圈辅助工具(WepOke),太坑了其实真的有挂(有挂教程)-哔哩哔哩;最新版202...
玩家必用(pokerrrr2)... 大家肯定在之前pokerrrr2或者pokerrrr2中玩过玩家必用(pokerrrr2)外挂透明挂...
推荐十款!微信雀神麻将设置才赢... 推荐十款!微信雀神麻将设置才赢(透视)太坑了竟然真的有挂(有挂介绍)-哔哩哔哩1、每一步都需要思考,...
分享认知!边锋麻将有挂,wep... 分享认知!边锋麻将有挂,wepoker开挂作弊详细,详细有挂(有挂规律)-哔哩哔哩这是由厦门游乐互动...
我来教大家(WPK数据)外挂透... 我来教大家(WPK数据)外挂透明挂辅助工具(软件)德州ai机器人(2025已更新)(哔哩哔哩);《W...
关于!小程序边锋干瞪眼辅助ap... 关于!小程序边锋干瞪眼辅助app(wEpOke),太坑了竟然真的有挂(有挂方法)-哔哩哔哩;小薇(透...
透视智能ai!雀神麻将小程序系... 透视智能ai!雀神麻将小程序系统规律(辅助挂)太坑了其实是真的有挂(有挂总结)-哔哩哔哩;广东雀神智...
透视透明!边锋麻将辅牌器,德扑... 透视透明!边锋麻将辅牌器,德扑之星辅助软件,详细有挂(有挂详情)-哔哩哔哩;亲们利用一分钟了解精致的...
总算清楚(Wepoke透视)外... 总算清楚(Wepoke透视)外挂透明挂辅助器安装(ai代打)透视辅助(2021已更新)(哔哩哔哩);...
一分钟了解!边锋斗地主透明器(... 一分钟了解!边锋斗地主透明器(wepOKE),太坑了果真是真的有挂(有挂透明)-哔哩哔哩是一款可以让...