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

相关内容

热门资讯

第8分钟带你科普!欢聚水鱼智能... 第8分钟带你科普!欢聚水鱼智能辅助,奇迹陕西辅助,揭秘教程(有挂细节)-哔哩哔哩;无需打开直接搜索加...
第一分钟带你科普!博乐填大坑图... 第一分钟带你科普!博乐填大坑图片,福州十八扑外卦,曝光教程(有挂规律)-哔哩哔哩;无需打开直接搜索加...
四分钟带你讲解!潮汕来物局开挂... 潮汕来物局开挂方法 无需打开直接搜索微信:136704302本司针对手游进行,选择我们的四大理由: ...
第三分钟带你透视!潮汕透视辅助... 第三分钟带你透视!潮汕透视辅助,决战卡五星开挂方法,必赢教程(有挂规律)-哔哩哔哩 【无需打开直接搜...
第8分钟带你开挂!天胡辅助脚本... 天蝎大厅辅助开挂教程视频分享装挂详细步骤在当今的网络游戏中,天蝎大厅辅助作为一种经典的娱乐方式,吸引...
第8分钟带你辅助!微信茶馆辅助... 第8分钟带你辅助!微信茶馆辅助器,全来潜山跑风破解版安卓,AI教程(揭秘有挂)-哔哩哔哩全来潜山跑风...
第五分钟带你发现!微信微乐游戏... 【亲,微信微乐游戏辅助脚本 这款游戏可以开挂的,确实是有挂的,很多玩家在这款微信微乐游戏辅助脚本中打...
5分钟带你辅助!wepoker... 5分钟带你辅助!wepoker插件程序,兴动互娱辅助器视频,大神讲解(新版有挂)-哔哩哔哩【无需打开...
第九分钟带你透视!新上游辅助,... 第九分钟带你透视!新上游辅助,悠闲卡五星辅助,攻略教程!(存在有挂)-哔哩哔哩1、下载安装好悠闲卡五...
十分钟带你透视!湖湘互娱牛牛,... 十分钟带你透视!湖湘互娱牛牛,胡乐辅助脚本,实用技巧(证实有挂)-哔哩哔哩>>您好:软件加薇1367...