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

相关内容

热门资讯

揭秘几款"新海贝辅助... 揭秘几款"新海贝辅助"开挂(软件)辅助软件证实有挂-教你教程;无需打开直接搜索微信(13670430...
推荐十款"开心泉州辅... 推荐十款"开心泉州辅助"开挂(平台)辅助平台有挂讲解-力荐教程这是一款可以让一直输的玩家,快速成为一...
透视好友"白银胡乐辅... 大家好,今天小编来为大家解答白银胡乐辅助脚本下载这个问题咨询软件客服可以免费测试直接加微信(1367...
玩家爆料"微乐小程序... 玩家爆料"微乐小程序晃晃脚本"开挂(下载)辅助下载有挂功能-第三方教程这是一款可以让一直输的玩家,快...
一分钟教你"微信新版... 一分钟教你"微信新版518互游辅助"开挂(平台)辅助平台有挂技巧-高科技教程您好:微信新版518互游...
最新技巧"越乡游辅助... 最新技巧"越乡游辅助器"开挂(神器)辅助神器竟然有挂-曝光教程越乡游辅助器ai黑科技系统规律教程开挂...
信息共享"超凡辅助软... 信息共享"超凡辅助软件"开挂(软件)辅助软件确实有挂-透明教程;无需打开直接搜索薇:13670430...
普及知识"佛手十三道... 普及知识"佛手十三道破解版安装"开挂(平台)辅助平台有挂规律-德州论坛;无需打开直接搜索加薇1367...
揭秘几款"天天开心国... 揭秘几款"天天开心国王辅助"开挂(脚本)辅助脚本有挂解惑-揭秘攻略天天开心国王辅助ai黑科技系统规律...
推荐攻略"爱玩联盟辅... >>您好:爱玩联盟辅助器确实是有挂的,很多玩家在这款爱玩联盟辅助器游戏中打牌都会发现很多用户的牌特别...