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文件中添加通知的渠道信息,以及在通知中使用的图标和资源文件。

相关内容

热门资讯

今日!aa poker辅助包(... 您好,德州扑克游戏辅助这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩...
透视苹果版!wepoker透视... 透视苹果版!wepoker透视脚本是什么(透视)边锋老友填大坑辅助(一贯存在有辅助下载)-哔哩哔哩一...
据悉!wepokerplus脚... 据悉!wepokerplus脚本(透视)途游破解版无限钻石(一直真的有辅助平台)-哔哩哔哩1、起透看...
连日来!hhpoker辅助器视... 连日来!hhpoker辅助器视频(透视)越乡游金花辅助(其实真的有辅助软件)-哔哩哔哩1、点击下载安...
据统计!hhpoker德州牛仔... 据统计!hhpoker德州牛仔视频(透视)微信微乐辅助器下载(原来有辅助下载)-哔哩哔哩1、很好的工...
近年来!aapoker俱乐部靠... 近年来!aapoker俱乐部靠谱吗(透视)途游四川小程序规律(一贯有辅助下载)-哔哩哔哩1、全新机制...
连日来!hhpkoer辅助器(... 连日来!hhpkoer辅助器(透视)微信边锋辅助软件(真是是有辅助app)-哔哩哔哩1、上手简单,内...
为了进一步!hhpoker到底... 为了进一步!hhpoker到底可以作必弊码(透视)闲逸透视app安装步骤详解(真是是真的辅助软件)-...
透视辅助!pokerrrr2辅... 透视辅助!pokerrrr2辅助(透视)新道游开挂(真是有辅助软件)-哔哩哔哩1、新道游开挂公共底牌...
出乎意料的是!约局吧app有挂... 出乎意料的是!约局吧app有挂吗(透视)小程序牵手跑辅助器(确实真的有辅助神器)-哔哩哔哩1)小程序...