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、操作简单,无需佛...
曝光透视!werplan外卦神... 曝光透视!werplan外卦神器!竟然存在有辅助神器(有挂细节)-哔哩哔哩1)werplan外卦神器...
关于透视!哈糖大菠萝可以开挂吗... 关于透视!哈糖大菠萝可以开挂吗!切实一直都是有辅助app(详细教程)-哔哩哔哩1、许多玩家不知道哈糖...
科普透视!佛手大菠萝辅助!总是... 科普透视!佛手大菠萝辅助!总是是有辅助软件(有挂功能)-哔哩哔哩1、下载好佛手大菠萝辅助脚本下载之后...
揭幕透视!竞技联盟透视!竟然是... 揭幕透视!竞技联盟透视!竟然是有辅助脚本(有挂透明挂)-哔哩哔哩1、实时竞技联盟透视透视辅助更新:用...
分享透视!佛手在线有挂吗!真是... 分享透视!佛手在线有挂吗!真是是真的有辅助app(有挂辅助)-哔哩哔哩;1、每一步都需要思考,不同水...
总结透视!大菠萝免费辅助!一直... 总结透视!大菠萝免费辅助!一直是真的有辅助方法(确实有挂)-哔哩哔哩;1、下载好大菠萝免费辅助脚本下...
开挂透视!拱趴大菠萝有什么挂!... 开挂透视!拱趴大菠萝有什么挂!竟然真的有辅助脚本(有挂方略)-哔哩哔哩1)拱趴大菠萝有什么挂免费钻石...
了解透视!约局吧能不能开挂!真... 了解透视!约局吧能不能开挂!真是真的是有辅助app(有挂分析)-哔哩哔哩1、全新机制【约局吧能不能开...
解迷透视!德州透视是真的吗!一... 解迷透视!德州透视是真的吗!一直是真的有辅助插件(讲解有挂)-哔哩哔哩德州透视是真的吗透视方法中分为...