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

相关内容

热门资讯

透视计算!吉祥填大坑小程序辅助... 吉祥填大坑小程序辅助是一款专注玩家量身打造的游戏记牌类型软件,在吉祥填大坑小程序辅助这款游戏中我们可...
玩家必备教程!新二号辅助下载,... 【亲,新二号辅助下载 这款游戏可以开挂的,确实是有挂的,很多玩家在这款新二号辅助下载中打牌都会发现很...
一分钟带你了解!边锋干瞪眼io... 一分钟带你了解!边锋干瞪眼ios辅助微信,决战卡五星辅助器(有挂技术开挂辅助器);无需打开直接搜索薇...
透视规律!卡五星辅助神器,po... 透视规律!卡五星辅助神器,pokemmo脚本辅助下载(辅助挂)详细开挂辅助安装;无需打开直接搜索薇:...
玩家必看攻略!好运南通长牌辅助... 玩家必看攻略!好运南通长牌辅助,樱花之盛辅助软件(确实有挂开挂辅助下载);打开点击测试直接进入微信(...
透视数据!潮汕老友麻将开挂,p... 透视数据!潮汕老友麻将开挂,pokermaster破解版(辅助挂)详细开挂辅助神器;无需打开直接搜索...
必备攻略!微信小程序自动透视微... 必备攻略!微信小程序自动透视微乐,玖游卡五星辅助(有挂技术辅助神器);无需打开直接搜索加薇13670...
透视辅助!欢乐达人正版脚本,哈... 哈糖大菠萝破解器开挂教程视频分享装挂详细步骤在当今的网络游戏中,哈糖大菠萝破解器作为一种经典的娱乐方...
玩家科普!传送屋没激k辅助器下... >>您好:传送屋没激k辅助器下载确实是有挂的,很多玩家在这款传送屋没激k辅助器下载游戏中打牌都会发现...
透明了解!哥哥打大a辅助,wp... 透明了解!哥哥打大a辅助,wpk软件是正规的吗(辅助挂)详细开挂辅助工具;无需打开直接搜索加(薇:1...