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

相关内容

热门资讯

十分钟了解!美猴王辅助,创思维... 十分钟了解!美猴王辅助,创思维激k辅助控制器(原来是真的挂)-哔哩哔哩小薇(透视辅助)致您一封信;亲...
2分钟揭幕!闲逸碰胡辅助器,九... 2分钟揭幕!闲逸碰胡辅助器,九酷互娱辅助(其实存在有挂)-哔哩哔哩暗藏猫腻,小编详细说明闲逸碰胡辅助...
2分钟揭幕!皮皮衡阳字牌黑科技... 2分钟揭幕!皮皮衡阳字牌黑科技视频,钱塘十水三挂件(其实存在有挂)-哔哩哔哩皮皮衡阳字牌黑科技视频软...
3分钟科普!湖南赣湘互娱辅助,... 3分钟科普!湖南赣湘互娱辅助,微信牵手跑辅助(原来是有挂)-哔哩哔哩在进入湖南赣湘互娱辅助辅助挂后,...
一分钟推荐!天酷互娱有辅助工具... 一分钟推荐!天酷互娱有辅助工具嘛,边锋老友填大坑辅助(真是是真的挂)-哔哩哔哩1、每一步都需要思考,...
十分钟总结!潮汕掌上娱辅助器,... 十分钟总结!潮汕掌上娱辅助器,中至余干小程序辅助安装(其实真的有挂)-哔哩哔哩1、超多福利:超高返利...
第四分钟解谜!关春天凑一桌辅助... 第四分钟解谜!关春天凑一桌辅助,胡乐辅助脚本(确实是有挂)-哔哩哔哩暗藏猫腻,小编详细说明关春天凑一...
四分钟详情!皇豪互娱控制系统a... 四分钟详情!皇豪互娱控制系统app,天天福建十三兵修改器(原来真的有挂)-哔哩哔哩1、天天福建十三兵...
第8分钟外挂!蜀山四川辅助,皮... 第8分钟外挂!蜀山四川辅助,皮皮跑子胡子修改器(一贯是真的挂)-哔哩哔哩1、打开软件启动之后找到中间...
九分钟揭幕!一乐棋牌辅助器,w... 九分钟揭幕!一乐棋牌辅助器,wepoker辅助脚本(一直真的有挂)-哔哩哔哩1、许多玩家不知道一乐棋...