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文件中声明了相关权限和服务。

相关内容

热门资讯

教会透视"wepok... 教会透视"wepoker有没有挂透视挂"开挂(透视)辅助插件(一分钟揭秘必赢方法)教会透视"wepo...
7分钟开挂!微信微乐辅助器下载... 您好:这款福建天天开心辅助软件大全游戏是可以开挂的,确实是有挂的,很多玩家在这款福建天天开心辅助软件...
第六分钟透视!广西老友玩方片破... 广西老友玩方片破解是一款专注玩家量身打造的游戏记牌类型软件,在广西老友玩方片破解这款游戏中我们可以记...
教会透视"安卓wep... 教会透视"安卓wepoker德州透视挂下载"开挂(透视)辅助软件(揭秘真相高科技教程)教会透视"安卓...
6分钟开挂!人海大厅挂件怎么买... 6分钟开挂!人海大厅挂件怎么买,来物局怎么开挂(2分钟细说开挂辅助软件);亲,人海大厅挂件怎么买这款...
发现透视"wepok... 发现透视"wepoker发牌算法"开挂(透视)辅助神器(玩家交流新版2026教程)发现透视"wepo...
四分钟辅助!山西奇迹打锅子辅助... 山西奇迹打锅子辅助 无需打开直接搜索微信:136704302本司针对手游进行,选择我们的四大理由: ...
正版透视"wepok... 正版透视"wepoker是不是有人用挂"开挂(透视)辅助脚本(一分钟了解扑克教程)正版透视"wepo...
第3分钟开挂!潮汕木虱辅助下载... 第3分钟开挂!潮汕木虱辅助下载,中至余干破解器(分享开挂内幕开挂辅助安装)【无需打开直接搜索加薇13...
科技透视"wrpok... 科技透视"wrpoker透视挂真的吗"开挂(透视)辅助工具(揭秘一下曝光教程)【福星临门,好运相随】...