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

相关内容

热门资讯

如何分辨真伪"新天道... 如何分辨真伪"新天道辅助软件怎么样"开挂(神器)辅助神器有挂辅助-2026教程>>您好:软件加136...
一分钟了解"欢聚水鱼... 欢聚水鱼辅助插件 无需打开直接搜索微信:136704302本司针对手游进行,选择我们的四大理由: 1...
总算了解"五十k辅助... 总算了解"五十k辅助"开挂(透视)辅助透视果真有挂-AI教程>>您好:软件加薇136704302中联...
盘点十款"poker... 盘点十款"pokernow辅助工具"开挂(脚本)辅助脚本有挂规律-我来教教你 【无需打开直接搜索加薇...
科技新动态"四川麻将... 科技新动态"四川麻将口诀顺口溜"开挂(平台)辅助平台真的有挂-总结教程 【无需打开直接搜索加薇136...
总算明白"微信闲来辅... 总算明白"微信闲来辅助神器"开挂(平台)辅助平台确实有挂-2026新版总结这是一款可以让一直输的玩家...
透视肯定"摸一把游戏... 您好:这款摸一把游戏跑得快辅助游戏是可以开挂的,确实是有挂的,很多玩家在这款摸一把游戏跑得快辅助游戏...
透视规律"八仙游戏辅... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...
揭秘真相"微信小程序... 揭秘真相"微信小程序家乡大贰辅助器"开挂(工具)辅助工具有挂猫腻-辅助教程 >>您好:软件加薇136...
总算明白"wepok... wepoker私人局规律 无需打开直接搜索微信:136704302本司针对手游进行,选择我们的四大理...