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

相关内容

热门资讯

第2分钟了解!八大碗麻将辅牌器... 第2分钟了解!八大碗麻将辅牌器购买(辅助挂)起初真的是有挂(专业辅助攻略教程)-哔哩哔哩是一款可以让...
一分钟了解!凉山跑得快有辅助工... 一分钟了解!凉山跑得快有辅助工具(辅助挂)其实存在有挂(专业辅助透牌教程)-哔哩哔哩;凉山跑得快有辅...
第1分钟了解!掌酷十三张赢分小... 第1分钟了解!掌酷十三张赢分小秘诀(辅助挂)都是真的有挂(专业辅助wpk教程)-哔哩哔哩;最新版20...
第1分钟了解!中至鹰潭麻将有挂... 第1分钟了解!中至鹰潭麻将有挂(辅助挂)都是是真的有挂(专业辅助2025新版教程)-哔哩哔哩;亲,有...
第二分钟了解!天天贵阳麻将插件... 第二分钟了解!天天贵阳麻将插件(辅助挂)从来存在有挂(专业辅助细节方法)-哔哩哔哩;天天贵阳麻将插件...
第6分钟了解!中至赣州有猫腻(... 第6分钟了解!中至赣州有猫腻(辅助挂)原来是有挂(专业辅助玩家教你)-哔哩哔哩;大家肯定在之前中至赣...
第一分钟了解!中至鹰潭麻将有挂... 第一分钟了解!中至鹰潭麻将有挂(辅助挂)最初是真的有挂(专业辅助AI教程)-哔哩哔哩;超受欢迎的中至...
2分钟了解!决战十三水ios版... 2分钟了解!决战十三水ios版辅助器(辅助挂)从前是真的有挂(专业辅助普及教程)-哔哩哔哩是一款可以...
9分钟了解!越乡游十三水辅助器... 9分钟了解!越乡游十三水辅助器(辅助挂)先前是有挂(专业辅助靠谱教程)-哔哩哔哩是一款可以让一直输的...
第五分钟了解!多乐微信小程序免... 您好,多乐微信小程序免费辅助器这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很...