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

相关内容

热门资讯

正版外挂石家庄麻将外挂多功能A... 正版外挂石家庄麻将外挂多功能AI攻略,石家庄麻将真是是真的有外挂攻略1、游戏颠覆性的策略玩法,独创攻...
WPK透视版课程!约局吧德州透... WPK透视版课程!约局吧德州透视,红龙扑克ai多功能透视挂脚本1、约局吧德州透视有没有辅助教程、约局...
正版辅助乐天棋牌辅助多功能AI... 正版辅助乐天棋牌辅助多功能AI教程,乐天棋牌都是真的有辅助教程1、全新机制【乐天棋牌ai辅助工具激活...
WPK作弊方案!aapoker... WPK作弊方案!aapoker透视插件,智星菠萝德州ai多功能透视挂插件1)aapoker透视插件辅...
正版作弊器哥哥杭州麻将作弊器多... 正版作弊器哥哥杭州麻将作弊器多功能AI工具,哥哥杭州麻将竟然存在有作弊器工具1、实时哥哥杭州麻将透视...
WPK购买窍要!红龙poker... WPK购买窍要!红龙poker辅助平台,微扑克ai多功能辅助器插件1、红龙poker辅助平台辅助器安...
正版作弊器红心无锡麻将作弊器多... 正版作弊器红心无锡麻将作弊器多功能AI教程,红心无锡麻将真是有作弊器教程暗藏猫腻,小编详细说明红心无...
WPK下载策略!uupoker... WPK下载策略!uupoker有透视吗,WePoKerai多功能辅助器脚本在进入uupoker有透视...
WPK俱乐部手筋!大菠萝789... WPK俱乐部手筋!大菠萝789辅助器下载,菠萝智星德州ai多功能透视挂app1、下载好大菠萝789辅...
正版辅助器心悦吉林麻将辅助器多... 正版辅助器心悦吉林麻将辅助器多功能AI方法,心悦吉林麻将一直真的是有辅助器方法运心悦吉林麻将辅助工具...