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

相关内容

热门资讯

十分钟带你了解!欢乐联盟免费辅... 十分钟带你了解!欢乐联盟免费辅助(辅助挂)教程辅助外挂开挂辅助安装(一直真的有挂)>>您好:软件加薇...
透视透视"微信小程序... 透视透视"微信小程序游戏破解微乐游戏"开挂(透视)辅助插件(一直真的有挂)-哔哩哔哩;一、微信小程序...
9分钟带你了解!决战卡五星必赢... 您好:这款决战卡五星必赢神器游戏是可以开挂的,确实是有挂的,很多玩家在这款决战卡五星必赢神器游戏中打...
透视智能ai"顺欣茶... 《透视智能ai"顺欣茶楼辅助视频"开挂(透视)辅助插件(一直真的有挂的)-哔哩哔哩》 顺欣茶楼辅助视...
第3分钟带你了解!决胜麻架胡易... 第3分钟带你了解!决胜麻架胡易辅助(辅助挂)2024教程外挂开挂辅助插件(其实是有挂);无需打开直接...
盘点一款"边锋老友辅... 盘点一款"边锋老友辅助器"开挂(透视)辅助软件(原来确实是有挂)-哔哩哔哩;边锋老友辅助器最新软件透...
五分钟带你了解!九游破解辅助插... 五分钟带你了解!九游破解辅助插件官网(透视挂)透视app外挂开挂辅助脚本(原来真的有挂);无需打开直...
透视私人局"瓜瓜丰城... 透视私人局"瓜瓜丰城双剑旧版攻略"开挂(透视)辅助工具(其实是有挂)-哔哩哔哩;1、这是跨平台的瓜瓜...
2分钟带你了解!欢乐卡五星辅助... 欢乐卡五星辅助工具是一款专注玩家量身打造的游戏记牌类型软件,在欢乐卡五星辅助工具这款游戏中我们可以记...
实测分享"奇迹陕西游... 实测分享"奇迹陕西游戏辅助器"开挂(透视)辅助下载(一直是有挂)-哔哩哔哩;奇迹陕西游戏辅助器是一项...