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

相关内容

热门资讯

免费测试版"微信小程... 免费测试版"微信小程序牵手辅助"开挂(透视)辅助平台(其实是真的有挂的)-哔哩哔哩;微信小程序牵手辅...
5分钟带你了解!麻友圈安全版插... 您好:麻友圈安全版插件这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌...
八分钟带你发现!蜀山四川破解好... 蜀山四川破解好友版辅助是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需要的用户可以...
一分钟揭秘"创思维激... 一分钟揭秘"创思维激k透视挂"开挂(透视)辅助安装(原来确实是有挂)-哔哩哔哩;最新版2026是一款...
第六分钟带你了解!牵手跑得软件... 第六分钟带你了解!牵手跑得软件(透视挂)透视神器外挂开挂辅助平台(果然有挂);无需打开直接搜索加(薇...
第2分钟带你辅助!网易棋牌辅助... 大家好,今天小编来为大家解答网易棋牌辅助器这个问题咨询软件客服可以免费测试直接加微信(1367043...
终于懂了"广西老友玩... 《终于懂了"广西老友玩游戏辅助器"开挂(透视)辅助插件(果然确实有挂的)-哔哩哔哩》 广西老友玩游戏...
三分钟带你了解!小程序66徐州... 三分钟带你了解!小程序66徐州辅助(透视挂)查到实测外挂开挂辅助工具(原来真的有挂);无需打开直接搜...
第一分钟带你开挂!浙江宝宝游戏... 第一分钟带你开挂!浙江宝宝游戏辅助器,贪吃蛇辅助器2022,曝光教程(真是有挂)-哔哩哔哩【无需打开...
盘点一款"拱趴大菠萝... 《盘点一款"拱趴大菠萝有辅助工具吗"开挂(透视)辅助平台(果然是有挂的)-哔哩哔哩》 拱趴大菠萝有辅...