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

相关内容

热门资讯

透视好牌"皇豪互娱科... 透视好牌"皇豪互娱科技软件"开挂(透视)wepoker作弊视频(真实有挂);大家肯定在之前或者中玩过...
带你了解"皮皮胡子辅... 带你了解"皮皮胡子辅助"开挂(透视)哈糖大菠萝可以开挂吗(有挂实锤);最新版2026是一款经典耐玩的...
最新技巧"拱趴大菠萝... 最新技巧"拱趴大菠萝辅助"开挂(透视)wepoker代打辅助(有挂细节);拱趴大菠萝辅助是一项拱趴大...
必备辅助推荐"微信小... 必备辅助推荐"微信小程序家长大贰辅助工具"开挂(透视)pokermaster修改器(有挂教程);1、...
揭秘"hhpoker... 揭秘"hhpoker底牌透视脚本"开挂(透视)wepoker插件功能辅助器(有挂方略);小薇(透视辅...
我来教教大家"蜜瓜大... 我来教教大家"蜜瓜大厅辅助下载"开挂(透视)wejoker私人辅助软件(有挂秘诀);蜜瓜大厅辅助下载...
透视科技"新道游智能... 透视科技"新道游智能辅助器"开挂(透视)wepoker有辅助器吗(有挂细节);1、超多福利:超高返利...
透视黑科技"福州十八... 透视黑科技"福州十八扑外卦视频"开挂(透视)fishpoker透视底牌(有挂方式);福州十八扑外卦视...
分辨真假"衢州都莱软... 分辨真假"衢州都莱软件辅助器"开挂(透视)hhpoker为什么一直输(有挂教程);1、完成的残局,帮...
详细说明"宝宝浙江游... 详细说明"宝宝浙江游戏真的有辅助嘛"开挂(透视)wepoker可以免费玩吗(真是有挂);最新版本免费...