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

相关内容

热门资讯

透视讲解!红龙poker脚本,... 1、透视讲解!红龙poker脚本,德普之星怎么作弊,大神推荐(有挂教学)。2、德普之星怎么作弊透视辅...
透视模拟器!wepoker作弊... 透视模拟器!wepoker作弊辅助,aapoker透视脚本,安装教程(最初真的是有挂);亲真的是有正...
透视辅助!德普之星辅助功能如何... 您好,德普之星辅助功能如何打开这款游戏可以开挂的,确实是有挂的,需要了解加Q群【1067239143...
透视存在!wepoker透视脚... 大家肯定在之前wepoker透视脚本免费下载或者wepoker透视脚本免费下载中玩过透视存在!wep...
透视数据!智星德州菠萝插件官网... 1、透视数据!智星德州菠萝插件官网,wpk透视辅助方法,普及知识(有挂规律);该软件可以轻松地帮助玩...
透视计算!wpk有没有脚本,w... 透视计算!wpk有没有脚本,wepoker辅助透视软件,详细教程(总是存在有挂)1、让任何用户在无需...
透视透视!hhpoker免费透... 透视透视!hhpoker免费透视脚本,德普之星怎么作弊,大神普及(有挂教程)1、每一步都需要思考,不...
透视科技!wepoker透视,... 大家肯定在之前wepoker透视或者wepoker透视中玩过透视科技!wepoker透视,wepok...
透视工具!wpk脚本下载,aa... 透视工具!wpk脚本下载,aapoker辅助功能,终于知道(有挂教学)(1)透视工具!wpk脚本下载...
透视软件!德普之星有没有挂,约... 透视软件!德普之星有没有挂,约局吧辅助器,必赢方法(确实有挂)需要回顾用户提供的搜索结果,比如,提到...