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

相关内容

热门资讯

透视辅助"aapok... 透视辅助"aapoker怎么设置提高好牌几率"详细辅助分享教程(有人玩透视);致您一封信;亲爱aap...
透视辅助"hhpok... 透视辅助"hhpoker是正品吗"详细辅助AI教程(辅助是真的假的教程);hhpoker是正品吗软件...
透视好牌"德普之星辅... 透视好牌"德普之星辅助工具如何设置"详细辅助详细教程(软件教程)是由北京得德普之星辅助工具如何设置黑...
透视规律"悦扑克脚本... 透视规律"悦扑克脚本"详细辅助2025版教程(有有挂规律教程)关于悦扑克脚本机制的,其中提到了后台系...
透视规律"poker... 透视规律"poker world辅助"详细辅助2025新版(私人局透视方法神器)准备好在poker ...
透视插件"wepok... 透视插件"wepoker有辅助工具吗"详细辅助必赢方法(作弊方法攻略)这是由厦门游乐互动科技有限公司...
透视模拟器"poke... 透视模拟器"pokemmo免费脚本"详细辅助普及教程(万能挂技巧);人气非常高,ai更新快且高清可以...
透视好牌"pokep... 透视好牌"pokeplus脚本"详细辅助实用技巧(私人局俱乐部透视)准备好在pokeplus脚本ia...
透视苹果版"wepo... 自定义wepoker怎么设置盖牌系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专用辅...
透视教学"wepok... 透视教学"wepoker透视脚本免费app"详细辅助技巧教程(私人辅助器透明);小薇(透视辅助)致您...