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

相关内容

热门资讯

热门推荐!吉祥填大坑的破解方法... 您好:吉祥填大坑的破解方法这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户...
玩家科普!中至赣州黑科技辅助软... 玩家科普!中至赣州黑科技辅助软件,四川游戏家园破解,AI教程(传授有开挂辅助器);无需打开直接搜索打...
一分钟揭秘!越乡游义乌透视软件... 一分钟揭秘!越乡游义乌透视软件,新518互游脚本下载,详细教程(详细有开挂辅助插件);无需打开直接搜...
技术分享!手游游戏挂机辅助,决... 技术分享!手游游戏挂机辅助,决战卡五星辅助看牌器,AI教程(盘点有开挂辅助器);无需打开直接搜索打开...
科普常识!约局吧黑科技辅助器,... 您好:约局吧黑科技辅助器这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的...
玩家亲测!微乐山西小程序破解器... 玩家亲测!微乐山西小程序破解器,卡农大厅辅助,科技教程(分析有开挂辅助软件)1、下载安装好微乐山西小...
一起来讨论!盛世辅助工具,胡乐... 一起来讨论!盛世辅助工具,胡乐辅助脚本是真的假的,详细教程(通报有开挂辅助插件);无需打开直接搜索加...
每日必看教程!新财神正版辅助挂... 每日必看教程!新财神正版辅助挂,新祥心有挂吗,2026新版总结(盘点有开挂辅助平台);无需打开直接搜...
科技新动态!余干五十k攻略,七... 科技新动态!余干五十k攻略,七千在线辅助,微扑克教程(细节有开挂辅助平台);无需打开直接搜索打开薇:...
实测分享!家乡大贰小程序辅助器... 实测分享!家乡大贰小程序辅助器,微信小程序微乐辅助器,技巧教程(了解有开挂辅助插件);无需打开直接搜...