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

相关内容

热门资讯

WPK辅助经验!aapoker... WPK辅助经验!aapoker怎么开辅助器,德扑之星ai多功能辅助器方法1、每一步都需要思考,不同水...
WPK透视版绝活!fishpo... WPK透视版绝活!fishpoker透视底牌,微扑克ai多功能辅助器方法1、让任何用户在无需fish...
WPK靠谱操作!AApoker... WPK靠谱操作!AApoker插件,菠萝智星德州ai多功能透视app亲,关键说明,AApoker插件...
WPK透视版诀窍!werpla... WPK透视版诀窍!werplan怎么作弊,红龙PoKerai多功能辅助器软件1、每一步都需要思考,不...
WPK工具手册!AApoker... WPK工具手册!AApoker使用,菠萝智星德州ai多功能透视方法进入游戏-大厅左侧-新手福利-激活...
WPK德州局指南!fishpo... WPK德州局指南!fishpoker透视,AApokerai多功能辅助工具fishpoker透视透视...
WPK透视版绝活儿!哈糖大菠萝... WPK透视版绝活儿!哈糖大菠萝有挂吗,菠萝智星德州ai多功能辅助插件1、玩家可以在哈糖大菠萝有挂吗透...
WPK插件策略!扑克之星辅助,... WPK插件策略!扑克之星辅助,红龙扑克ai多功能辅助器技巧扑克之星辅助透视方法中分为三种模型:扑克之...
WPK软件手册!AApoker... WPK软件手册!AApoker拿好牌,红龙扑克ai多功能辅助器教程1、金币登录送、破产送、升级送、活...
WPK安卓资料!佛手在线大菠萝... WPK安卓资料!佛手在线大菠萝技巧,智星菠萝德州ai多功能透视挂app1、每一步都需要思考,不同水平...