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

相关内容

热门资讯

详细说明!四川游戏家园破解,天... 详细说明!四川游戏家园破解,天天开心王国怎么辅助(有挂秘笈辅助开挂脚本)1、下载安装好四川游戏家园破...
必知教程!奇迹手机辅助脚本怎么... 大家好,今天小编来为大家解答奇迹手机辅助脚本怎么下载这个问题咨询软件客服可以免费测试直接加微信(13...
六分钟了解!广东雀神智能插件安... 【亲,广东雀神智能插件安装软件 这款游戏可以开挂的,确实是有挂的,很多玩家在这款广东雀神智能插件安装...
科技介绍!云麻圈修改器,创思维... 科技介绍!云麻圈修改器,创思维辅助软件(有挂猫腻辅助开挂挂)1、下载安装好创思维辅助软件,进入游戏主...
攻略讲解!皮皮辅助软件下载,南... 攻略讲解!皮皮辅助软件下载,南昌微乐自建房辅助(有挂教学辅助工具)这是一款可以让一直输的玩家,快速成...
研究成果!新玄龙开挂图片片,兴... 研究成果!新玄龙开挂图片片,兴动休闲辅助(有挂解密辅助开挂挂);无需打开直接搜索打开薇:136704...
一分钟了解!h5大厅反杀,丽水... 一分钟了解!h5大厅反杀,丽水都莱app辅助(有挂秘籍开挂辅助软件);无需打开直接搜索加(薇:136...
总算了解!随意玩房卡辅助,闲逸... 闲逸辅助神器免费开挂教程视频分享装挂详细步骤在当今的网络游戏中,闲逸辅助神器免费作为一种经典的娱乐方...
一分钟了解!荔枝竞技通用辅助器... 一分钟了解!荔枝竞技通用辅助器,科乐填大坑破解游戏(有挂工具辅助软件);无需打开直接搜索微信(136...
大家学习交流!微信小程序雀神挂... 大家学习交流!微信小程序雀神挂件价格,瓜瓜丰城双剑旧版攻略(有挂猫腻辅助软件);无需打开直接搜索加(...