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、微乐小程序多乐辅助...
黑科技透视器!微乐小程序微乐房... 黑科技透视器!微乐小程序微乐房间怎么开挂(透视器),微乐吉林麻将确实真的有透视挂方法1、这是跨平台的...
黑科技透视器!微乐自建房免费脚... 黑科技透视器!微乐自建房免费脚本哪个最好用(透视器),微乐南京敞开头好像是真的有透视挂方法1、进入游...
黑科技透视挂!微乐广西小程序插... 黑科技透视挂!微乐广西小程序插件(透视挂),微乐小程序微乐游戏都是是真的有透视挂脚本1、实时微乐广西...
黑科技透视挂!微乐小程序辅助免... 您好,微乐小程序辅助免费这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多...
黑科技辅助器!微乐脚本辅助器(... 黑科技辅助器!微乐脚本辅助器(辅助器),微乐新余50k有确实有透视挂方法1)微乐脚本辅助器免费钻石:...
黑科技辅助器!微乐贵阳捉鸡麻将... 黑科技辅助器!微乐贵阳捉鸡麻将挂软件(辅助器),微乐贵阳捉鸡一直存在有透视挂攻略1、每一步都需要思考...
黑科技透视挂!微乐小程序黑科技... 黑科技透视挂!微乐小程序黑科技app入口(透视挂),微乐宁夏捉麻子其实有透视挂方法1、让任何用户在无...