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、微信小程序多乐辅助器系统规律...
七分钟外挂!宝宝浙江游戏开挂器... 七分钟外挂!宝宝浙江游戏开挂器,潮汕汇辅助神器(真是是真的挂)-哔哩哔哩1、宝宝浙江游戏开挂器系统规...
第5分钟外挂!南通长牌辅助,猎... 第5分钟外挂!南通长牌辅助,猎鱼达人破解版无限弹头(好像真的是有挂)-哔哩哔哩1、猎鱼达人破解版无限...
六分钟关于!创思维激k看底牌辅... 六分钟关于!创思维激k看底牌辅助,微友三代辅助(确实真的是有挂)-哔哩哔哩1、全新机制【创思维激k看...
第7分钟总结!今日长牌破解,中... 第7分钟总结!今日长牌破解,中至赣州冲关小程序辅助(其实存在有挂)-哔哩哔哩1、任何中至赣州冲关小程...
两分钟解密!阿拉游戏免费辅助器... 两分钟解密!阿拉游戏免费辅助器,水鱼辅助软件下载(原来有挂)-哔哩哔哩1)阿拉游戏免费辅助器辅助挂:...
第四分钟揭幕!微乐家乡麻辣自建... 第四分钟揭幕!微乐家乡麻辣自建房,闲聚app辅助软件(确实存在有挂)-哔哩哔哩运微乐家乡麻辣自建房辅...
7分钟解谜!闲逸平台辅助功能入... 7分钟解谜!闲逸平台辅助功能入口在哪里,心悦填大坑辅助(一直是有挂)-哔哩哔哩闲逸平台辅助功能入口在...
第十分钟详情!宝宝浙江游戏有挂... 第十分钟详情!宝宝浙江游戏有挂吗,微信小程序游戏破解器(总是真的有挂)-哔哩哔哩1、操作简单,无需注...
六分钟揭幕!创乐源辅助软件,贪... 六分钟揭幕!创乐源辅助软件,贪吃蛇辅助器(竟然真的是有挂)-哔哩哔哩1、很好的工具软件,可以解锁游戏...