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

相关内容

热门资讯

盘点十款!皮皮游戏辅助平台,w... 您好,皮皮游戏辅助平台这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家在...
揭秘!皮皮手游辅助,德普之星怎... 揭秘!皮皮手游辅助,德普之星怎么设置埋牌,透明教程(有挂讲解);揭秘!皮皮手游辅助,德普之星怎么设置...
必备教程!佛手大菠萝破解版io... 必备教程!佛手大菠萝破解版ios,wepoker辅助软件价格,玩家教你(有挂细节);1、让任何用户在...
重磅来袭!欢乐卡五星插件,约局... 重磅来袭!欢乐卡五星插件,约局吧如何查看是否有挂,2025教程(有挂方法)是一款可以让一直输的玩家,...
实操分享!随意玩辅助器,epo... 实操分享!随意玩辅助器,epoker有透视吗,2025新版(有挂透明挂);随意玩辅助器是一种具有地方...
盘点一款!天道辅助器使用教程,... 盘点一款!天道辅助器使用教程,wepoker透视有吗,存在挂教程(真实有挂);相信小伙伴都知道这个天...
记者爆料!牵手跑得软件,wep... 记者爆料!牵手跑得软件,wepoker高级辅助,总结教程(有挂助手);牵手跑得软件免费下载原版,在牵...
最新研发!维系小程序雀神挂件,... 最新研发!维系小程序雀神挂件,wepoker软件辅助程序,解密教程(果真有挂)是一款可以让一直输的玩...
实测发现!微乐河南小程序微乐辅... 实测发现!微乐河南小程序微乐辅助脚本,hhpoker是正品吗,新2025教程(有挂解密);1、这是跨...
一分钟秒懂!来几局辅助器开挂,... 一分钟秒懂!来几局辅助器开挂,hhpoker辅助挂是真的吗,透明挂教程(有挂方式);来几局辅助器开挂...