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

相关内容

热门资讯

热点推荐(AaPOKER)外挂... 热点推荐(AaPOKER)外挂透明挂辅助工具(智能)德州ai机器人(2024已更新)(哔哩哔哩);德...
记者揭秘!广东雀神辅助器微信插... 记者揭秘!广东雀神辅助器微信插件(透视)太坑了其实真的有挂(有挂技巧)-哔哩哔哩;玩家在广东雀神辅助...
热点推荐!边锋杭麻圈有挂(we... 此外,数据分析德州(边锋杭麻圈有挂)辅助神器app还具备辅助透视行为开挂功能,通过对客户边锋杭麻圈有...
推荐几款新版!边锋老友棋牌一直... 推荐几款新版!边锋老友棋牌一直输,德扑之心透视辅助,详细有挂(有挂规律)-哔哩哔哩;(需添加指定薇7...
玩家攻略(德扑ai机器人)外挂... 玩家攻略(德扑ai机器人)外挂透明挂辅助工具(俱乐部)透视辅助(2020已更新)(哔哩哔哩);亲,其...
重大通报!微信雀神小程序辅助插... 重大通报!微信雀神小程序辅助插件下载(辅助挂)太坑了确实真的有挂(有挂方法)-哔哩哔哩科技教程也叫必...
推荐一款!边锋游戏辅助器(we... 推荐一款!边锋游戏辅助器(wePokE),太坑了竟然真的有挂(有挂透明)-哔哩哔哩;玩家必备必赢加哟...
我来教大家!杭麻圈有外挂,私人... 我来教大家!杭麻圈有外挂,私人局wpk德州作弊教程,详细有挂(有挂方法)-哔哩哔哩,支持语音通讯、好...
透明辅助(德扑ai助手)外挂透... 透明辅助(德扑ai助手)外挂透明挂辅助软件(软件)德州ai机器人(2023已更新)(哔哩哔哩);德扑...
6分钟了解!雀神微信小程序开挂... 1、6分钟了解!雀神微信小程序开挂(辅助挂)太坑了确实是真的有挂(有挂透明)-哔哩哔哩;该软件可以轻...