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

相关内容

热门资讯

实测必看!潮汕激k脚本,天酷辅... 实测必看!潮汕激k脚本,天酷辅助器,详细神器(确实有挂)1、进入游戏-大厅左侧-新手福利-激活码辅助...
近期!wpk有作弊吗,智星德州... 近期!wpk有作弊吗,智星德州有脚本吗,本来真的是有挂(有挂解密)智星德州有脚本吗能透视中分为三种模...
大神推荐!科乐天天踢有没有挂作... 大神推荐!科乐天天踢有没有挂作弊,老友地方内蒙古辅助,详细挂(有挂秘笈)1、让任何用户在无需科乐天天...
网友热议!aapoker安装包... 网友热议!aapoker安装包怎么使用,德普之星辅助工具如何设置,本来真的有挂(有挂总结)1、德普之...
一分钟了解!德友汇辅助,科米台... 一分钟了解!德友汇辅助,科米台州麻将辅助,详细插件(有挂规律)1、打开软件启动之后找到中间准星的标志...
有玩家发现!佛手在线大菠萝技巧... 有玩家发现!佛手在线大菠萝技巧,德普辅助软件,总是是有挂(有挂教学)1、进入到德普辅助软件是否有挂之...
总算了解!决战十三水ios辅助... 总算了解!决战十三水ios辅助,手机挂机软件,详细攻略(有挂教程)决战十三水ios辅助脚本下载中分为...
据相关数据显示!aapoker... 据相关数据显示!aapoker辅助器是真的吗,德扑之星透视免费,原来确实有挂(有挂详情)1、进入游戏...
专业讨论!山西打锅子技巧,朋友... 专业讨论!山西打锅子技巧,朋友圈app辅助软件,详细软件(有挂技术)朋友圈app辅助软件透视方法中分...
规律辅助挂!wepoker俱乐... 规律辅助挂!wepoker俱乐部辅助,德普之星辅助器怎么用,真是真的有挂(有挂方略)德普之星辅助器怎...