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

相关内容

热门资讯

重大推荐!微乐辅助软件购买平台... 您好,微乐辅助软件购买平台这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩...
实测分享!微信西楚辅助,pok... 实测分享!微信西楚辅助,pokemmo辅助器脚本下载,微扑克教程(证实有挂);亲,有的,ai轻松简单...
总算了解!天天爱柳州麻将辅助器... 总算了解!天天爱柳州麻将辅助器,hhpoker可以开挂吗,AI教程(有挂细节);暗藏猫腻!天天爱柳州...
必备教程!微信广东雀神挂件辅助... 必备教程!微信广东雀神挂件辅助,wepoker到底有没有透视,攻略方法(有挂猫腻);必备教程!微信广...
盘点一款!花花生活圈开挂,哈糖... 盘点一款!花花生活圈开挂,哈糖大菠萝软件下载,技巧教程(有挂功能);花花生活圈开挂是一款益智类棋牌手...
分享个大家!微信小程序蜀山四川... 分享个大家!微信小程序蜀山四川辅助器,wpk控制牌是真的吗,解说技巧(有挂总结);1、点击下载安装,...
科技介绍!青龙辅助最新下载,p... 科技介绍!青龙辅助最新下载,pokeplus脚本,切实教程(有挂方法);1、让任何用户在无需AI插件...
盘点一款!陕西挖坑辅助,new... 【福星临门,好运相随】;盘点一款!陕西挖坑辅助,newpoker怎么安装脚本,科技教程(确实有挂);...
必备辅助推荐!家乡大二有没有辅... 必备辅助推荐!家乡大二有没有辅助,来玩app破解,必备教程(有挂神器);1、这是跨平台的家乡大二有没...
攻略讲解!微信小程序辅助器免费... 攻略讲解!微信小程序辅助器免费2.0苹果版,wepoker透视脚本免费下载,揭秘攻略(有挂详细);作...