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

相关内容

热门资讯

攻略讲解!德扑圈辅助挂多功能透... 攻略讲解!德扑圈辅助挂多功能透视工具,确实存在有挂(有挂技巧)1、玩家可以在德扑圈线上大神俱乐部对游...
一分钟揭秘!德扑圈辅助挂多功能... 一分钟揭秘!德扑圈辅助挂多功能透视工具,一贯真的是有挂(竟然有挂)1、进入到德扑圈是否有挂之后,能看...
一分钟了解!红龙poker辅助... 一分钟了解!红龙poker辅助挂多功能透视工具,总是是真的有挂(有挂总结)进入游戏-大厅左侧-新手福...
三分钟了解!德扑之星辅助挂多功... 三分钟了解!德扑之星辅助挂多功能透视工具,一贯是真的有挂(有挂攻略)1、玩家可以在德扑之星透视最简单...
带你了解!wpk辅助挂多功能透... 您好,wpk这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在这款游...
热点推荐!微扑克辅助挂多功能透... 热点推荐!微扑克辅助挂多功能透视工具,一直存在有挂(有挂实锤)该软件可以轻松地帮助玩家将微扑克外卦神...
科技分享!德扑圈辅助挂多功能透... 科技分享!德扑圈辅助挂多功能透视工具,竟然存在有挂(真的有挂)1、该软件可以轻松地帮助玩家将德扑圈辅...
交流学习经验!aapoker辅... 交流学习经验!aapoker辅助挂多功能透视工具,本来有挂(有挂秘籍)1、aapoker公共底牌简单...
玩家交流!WPK辅助挂多功能透... 玩家交流!WPK辅助挂多功能透视工具,真是是有挂(有挂方针)WPK透视方法中分为三种模型:WPK靠谱...
玩家攻略!wpk辅助挂多功能透... 玩家攻略!wpk辅助挂多功能透视工具,切实存在有挂(有挂方法)1、用户打开应用后不用登录就可以直接使...