Android推送在几秒后消失。
创始人
2024-08-21 21:00:44
0

以下是一个在Android中实现推送消息在几秒后消失的代码示例:

  1. 创建一个新的类NotificationUtils
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.NotificationCompat;

public class NotificationUtils {
    private static final int NOTIFICATION_ID = 1;
    private static final int DELAY_MILLIS = 3000; // 3秒

    public static void showNotification(Context context, String title, String message) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "channel_id")
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle(title)
                .setContentText(message)
                .setAutoCancel(true);

        Notification notification = builder.build();

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(NOTIFICATION_ID, notification);

        // 注册一个延迟的任务,在指定时间后取消通知
        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                notificationManager.cancel(NOTIFICATION_ID);
            }
        }, DELAY_MILLIS);
    }
}
  1. 在你的推送消息接收到的地方调用NotificationUtils.showNotification()方法来显示通知,例如在onMessageReceived()方法中:
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // 解析推送消息
    String title = remoteMessage.getData().get("title");
    String message = remoteMessage.getData().get("message");

    // 显示通知
    NotificationUtils.showNotification(getApplicationContext(), title, message);
}

请确保你已经创建了一个合适的通知渠道(channel_id)并在AndroidManifest.xml文件中声明了相关权限和服务。

相关内容

热门资讯

一分钟了解!大当家辅助脚本设置... 一分钟了解!大当家辅助脚本设置,福建天天开心辅助器,实测开挂辅助教程(有挂透视);无需打开直接搜索薇...
专业讨论!新518互游辅助,广... 专业讨论!新518互游辅助,广西友乐app辅助工具,曝光开挂辅助教程(真的有挂);无需打开直接搜索薇...
记者揭秘!边锋干瞪眼小程序辅助... 记者揭秘!边锋干瞪眼小程序辅助,对战互娱辅助系统,原来有开挂辅助教程(有挂助手);无需打开直接搜索加...
盘点几款!微乐透视辅助功能插件... 盘点几款!微乐透视辅助功能插件下载,微信小程序微乐辅助器,必看开挂辅助教程(存在有挂);无需打开直接...
每日必看!小程序卡五星辅助,顺... 每日必看!小程序卡五星辅助,顺欣茶楼开挂,正版开挂辅助教程(证实有挂);无需打开直接搜索加薇1367...
热点推荐!江湖悠悠手游攻略,越... 热点推荐!江湖悠悠手游攻略,越乡游辅助软件,实测开挂辅助教程(有挂方略);无需打开直接搜索打开薇:1...
科技新动态!爱玩联盟辅助,宁夏... 科技新动态!爱玩联盟辅助,宁夏划水辅助,分享开挂辅助教程(有挂辅助)1、下载安装好宁夏划水辅助,进入...
玩家科普!边锋干瞪眼小程序辅助... 玩家科普!边锋干瞪眼小程序辅助,对战互娱有辅助吗,了解开挂辅助教程(有挂功能);无需打开直接搜索打开...
科普攻略!多乐跑胡子辅助,新蜜... 您好:新蜜瓜大厅免费控制器这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户...
六分钟了解!渝都麻将开挂方法,... 六分钟了解!渝都麻将开挂方法,蘑菇云辅助怎么使用,盘点开挂辅助教程(有挂分析);无需打开直接搜索薇:...