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

相关内容

热门资讯

有挂秘籍开挂!全民内蒙古辅助,... 有挂秘籍开挂!全民内蒙古辅助,789大菠萝可以控制吗(推荐十款开挂辅助软件)您好:789大菠萝可以控...
确实有挂开挂!川滇互娱app辅... >>您好:川滇互娱app辅助确实是有挂的,很多玩家在这款川滇互娱app辅助游戏中打牌都会发现很多用户...
有挂规律开挂!微信小程序辅助器... 微信小程序辅助器出租 无需打开直接搜索微信:136704302本司针对手游进行,选择我们的四大理由:...
有挂教程开挂!赣州冲关辅助,情... 有挂教程开挂!赣州冲关辅助,情怀宜春辅助(科技新动态开挂辅助软件)您好:情怀宜春辅助这款游戏可以开挂...
有挂教程开挂!关春天开挂,德普... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...
存在有挂开挂!小程序牵手跑得快... 存在有挂开挂!小程序牵手跑得快辅助器,中至赣州黑科技辅助软件(如何分辨真伪开挂辅助下载)>>您好:软...
有挂技巧辅助!微乐老友广东辅助... 有挂技巧辅助!微乐老友广东辅助器,乐平讨赏挂(透视最新开挂辅助插件)微乐老友广东辅助器ai黑科技系统...
有挂讲解开挂!填大坑辅助器,老... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...
有挂分析辅助!授权二厅辅助,中... 有挂分析辅助!授权二厅辅助,中至赣州黑科技辅助软件视频(玩家必备科普开挂辅助软件)>>您好:软件加1...
有挂技巧辅助!腾威互娱 辅助工... 腾威互娱 辅助工具是一款专注玩家量身打造的游戏记牌类型软件,在腾威互娱 辅助工具这款游戏中我们可以记...