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

相关内容

热门资讯

推荐一款"赣牌圈的好... 推荐一款"赣牌圈的好牌几率"开挂(透视)hhpoker透视脚本视频(有挂实锤);是一款可以让一直输的...
分辨真假"h5新全游... 分辨真假"h5新全游辅助"开挂(透视)xpoker辅助助手(竟然有挂);h5新全游辅助中的10万兆豆...
透视攻略"wpk显示... 透视攻略"wpk显示有辅助"开挂(透视)wepoker辅助器(有挂工具);wepoker辅助器软件透...
避坑细节"海豹3+1... 【福星临门,好运相随】;避坑细节"海豹3+1辅助器"开挂(透视)德州hhpoker是真的吗(有挂教程...
专业讨论"花花生活圈... 专业讨论"花花生活圈辅助"开挂(透视)拱趴大菠萝有什么挂(有挂猫腻);软件透视开挂更新新赛季,主要更...
今日百科"盛世辅助&... 今日百科"盛世辅助"开挂(透视)wejoker辅助器要钱玩吗(有挂细节);1.盛世辅助 ai辅助创建...
六分钟了解"闲逸亲友... 【福星临门,好运相随】;六分钟了解"闲逸亲友圈辅助下载"开挂(透视)wepoker软件安装包(有挂攻...
专业讨论"玄龙辅助工... 专业讨论"玄龙辅助工具"开挂(透视)wepoker透视器免费(详细教程);致您一封信;亲爱玩家:《透...
今日百科"广西老友麻... 今日百科"广西老友麻将辅助器"开挂(透视)we-poker辅助软件教程(有挂猫腻);1、这是跨平台的...
必备教程"微信小程序... 必备教程"微信小程序途游辅助免费"开挂(透视)wpk插件(确实有挂);相信小伙伴都知道这个微信小程序...