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

相关内容

热门资讯

程序员教你!hhpoker万能... 程序员教你!hhpoker万能辅助器(辅助挂)真是是有挂(有挂规律辅助插件)1、很好的工具软件,可以...
记者揭秘!wepoker有脚本... 记者揭秘!wepoker有脚本吗(辅助挂)本来真的有挂(有挂详细辅助工具)该软件可以轻松地帮助玩家将...
科普分享!hhpoker哪个俱... 科普分享!hhpoker哪个俱乐部靠谱(辅助挂)都是存在有挂(有挂方法辅助工具)1、上手简单,内置详...
必备科技!hhpoker的辅助... 必备科技!hhpoker的辅助是真的吗(辅助挂)确实是有挂(有挂神器辅助工具)是不是有人用挂微扑克w...
我来教教你!aapoker辅助... 我来教教你!aapoker辅助工具安全吗(辅助挂)好像存在有挂(有挂头条辅助脚本)1、游戏颠覆性的策...
科技分享!aapoker辅助器... 科技分享!aapoker辅助器是真的吗(辅助挂)原来存在有挂(有挂透视辅助器)运辅助工具,进入游戏界...
解密关于!pokemmo手机脚... 解密关于!pokemmo手机脚本辅助器(辅助挂)一贯有挂(有挂神器辅助攻略)1)辅助插件:进一步探索...
必备科技!wepoker怎么设... 必备科技!wepoker怎么设置盖牌(辅助挂)一直真的有挂(有挂方式辅助脚本)1)有没有挂:进一步探...
专业讨论!wepoker透视脚... 专业讨论!wepoker透视脚本下载(辅助挂)都是真的有挂(有挂规律辅助工具)1、每一步都需要思考,...
大神推荐!wepoker辅助器... 大神推荐!wepoker辅助器安装包(辅助挂)原来有挂(有挂方针辅助软件)是不是有人用挂微扑克wpk...