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、三七互娱辅助器透视开挂公共底...
第九分钟辅助!微乐小程序黑科技... 第九分钟辅助!微乐小程序黑科技app入口,果然有辅助软件(有挂讲解)一、微乐小程序黑科技app入口可...
4分钟辅助!广东雀神智能插件安... 4分钟辅助!广东雀神智能插件安装辅助器,都是是真的有辅助挂(新版有挂)进入游戏-大厅左侧-新手福利-...
第8分钟辅助!上品斗地主游戏辅... 第8分钟辅助!上品斗地主游戏辅助,真是真的有辅助方法(有挂方法)1、操作简单,无需上品斗地主游戏辅助...
一分钟辅助!雀神智能插件安装价... 一分钟辅助!雀神智能插件安装价格,其实是真的有辅助器(有挂方略)一分钟辅助!雀神智能插件安装价格,其...
三分钟辅助!微乐小程序外辅助工... 三分钟辅助!微乐小程序外辅助工具,原来是有辅助技巧(有挂透明挂)进入游戏-大厅左侧-新手福利-激活码...
九分钟辅助!闲玩暗宝插件,原来... 九分钟辅助!闲玩暗宝插件,原来是真的有辅助app(证实有挂)1、下载好闲玩暗宝插件脚本下载之后点击打...
第三分钟辅助!情怀国粹麻将神器... 第三分钟辅助!情怀国粹麻将神器,其实是真的有辅助神器(有挂秘籍)1、许多玩家不知道情怀国粹麻将神器辅...
9分钟辅助!728游戏怎么控制... 9分钟辅助!728游戏怎么控制的,原来是有辅助挂(存在有挂)1、728游戏怎么控制的模拟器是什么优化...
第8分钟辅助!指尖四川辅助破解... 第8分钟辅助!指尖四川辅助破解版苹果,好像真的有辅助教程(存在有挂)1、金币登录送、破产送、升级送、...