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模拟器... 终于知道!wepoker模拟器哪个好用,wpk透视工作室,科技教程(有挂技巧);科技安装教程;136...
交流学习经验!wepoker辅... 交流学习经验!wepoker辅助器软件下载,wepoker软件安装包,我来教教你(有挂技巧);原来确...
一分钟了解!哈糖大菠萝有挂吗5... 一分钟了解!哈糖大菠萝有挂吗5个常用方法,wepoker一直输的号能继续打吗,教你攻略(有挂教程)这...
必看攻略!德州之星扫描器,we... 必看攻略!德州之星扫描器,wepoker怎么买辅助,解密教程(有挂透视)是一款可以让一直输的玩家,快...
我来教大家!德州透视是真的假的... 此外,数据分析德州(德州透视是真的假的)辅助神器app还具备辅助透视行为开挂功能,通过对客户德州透视...
玩家攻略!pokemmo手机版... 玩家攻略!pokemmo手机版脚本免费,wepoker私人局辅助,wepoke教程(有挂攻略)1、玩...
最新研发!aa poker辅助... 最新研发!aa poker辅助包,wepoker破解是真的还是假的,AA德州教程(有挂教程)关于we...
玩家必看教程!hhpoker免... 玩家必看教程!hhpoker免费透视脚本,aa poker辅助,力荐教程(有挂方法)是一款可以让一直...
重大通报!wepoker破解游... 重大通报!wepoker破解游戏盒子,wepoker破解器,可靠技巧(有挂透视);实战中需综合运用上...
重大发现!德普之星透视辅助插件... 重大发现!德普之星透视辅助插件,wepokerplus开挂,解密教程(有挂软件);致您一封信;亲爱德...