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

相关内容

热门资讯

来临!wejoker辅助脚本,... 来临!wejoker辅助脚本,德普之星私人局辅助免费,果然确实有挂(有挂方略)一、德普之星私人局辅助...
热点推荐!功夫川麻小程序辅助器... 热点推荐!功夫川麻小程序辅助器,琼崖辅助软件,详细技巧(有挂透明挂)1、每一步都需要思考,不同水平的...
有了最新消息!pokemmo手... 有了最新消息!pokemmo手机脚本,智星德州插件2024最新版,确实确实有挂(有挂头条)1、全新机...
一分钟揭秘!随意玩脚本辅助工具... 一分钟揭秘!随意玩脚本辅助工具透视,789大菠萝可以控制吗,详细方法(有挂规律)1、随意玩脚本辅助工...
随着!约局吧app有挂吗,德扑... 随着!约局吧app有挂吗,德扑之星辅助器app,都是是真的有挂(确实有挂)德扑之星辅助器app透视方...
今日重大通报!微乐家乡app下... 今日重大通报!微乐家乡app下载,微乐游戏小程序辅助器免费苹果版,详细教程(揭秘有挂)微乐游戏小程序...
目前来看!德州局怎么透视,德扑... 目前来看!德州局怎么透视,德扑之星辅助器app,切实是真的有挂(揭秘有挂)德扑之星辅助器app能透视...
盘点一款!南宁友乐辅助,功夫川... 盘点一款!南宁友乐辅助,功夫川麻辅助,详细挂(有挂分享)1、玩家可以在南宁友乐辅助透视最简单三个步骤...
今年以来!wepoker代打辅... 今年以来!wepoker代打辅助机器人,德扑之星辅助工具如何打开,真是真的有挂(揭秘有挂)1、该软件...
科普常识!凑一桌小程序辅助器,... 科普常识!凑一桌小程序辅助器,山西扣点子技巧,详细器(有挂分析)1、实时凑一桌小程序辅助器透视辅助更...