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

相关内容

热门资讯

第1分钟安装!微乐小程序黑科技... 第1分钟安装!微乐小程序黑科技,微乐陕西小程序辅助(开挂)果然真的有挂(2026)微乐小程序黑科技能...
2026版规律!微乐小程序黑科... 2026版规律!微乐小程序黑科技,微乐南昌辅助神器(透视)一贯有挂(哔哩哔哩)1、微乐南昌辅助神器破...
第7分钟透视!微乐小程序免费黑... 第7分钟透视!微乐小程序免费黑科技,微乐自建房插件如何安装(开挂)果然有挂(2026)1、第7分钟透...
据了解!微乐小程序免费黑科技,... 据了解!微乐小程序免费黑科技,陕西微乐小程序攻略(透视)切实真的有挂(哔哩哔哩)1、不需要AI权限,...
一分钟神器!微乐小程序黑科技,... 一分钟神器!微乐小程序黑科技,微乐小程序辅助开发(开挂)好像存在有挂(2026)1、微乐小程序黑科技...
做出回应!微乐小程序黑科技,微... 做出回应!微乐小程序黑科技,微乐自建房免费黑科技推荐(透视)竟然是真的挂(哔哩哔哩)1、任何微乐自建...
5分钟开挂!微乐小程序免费黑科... 5分钟开挂!微乐小程序免费黑科技,微乐家乡app下载(开挂)好像有挂(2026)1、该软件可以轻松地...
透视玄学!微乐小程序黑科技,微... 透视玄学!微乐小程序黑科技,微信小程序微乐破解器(透视)确实存在有挂(哔哩哔哩)1、微信小程序微乐破...
第8分钟辅助!微乐小程序免费黑... 第8分钟辅助!微乐小程序免费黑科技,微乐小程序晃晃脚本(开挂)其实是真的挂(2026)1、完成微乐小...
透视黑科技!微乐小程序黑科技,... 透视黑科技!微乐小程序黑科技,微乐自建房脚本使用安全吗(透视)好像有挂(哔哩哔哩)1、游戏颠覆性的策...