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

相关内容

热门资讯

了解透视!hhpoker底牌透... 了解透视!hhpoker底牌透视脚本,微乐家乡app下载,要领教程(有挂方法)-哔哩哔哩1、玩家可以...
专业透视!扑克之星辅助,微乐麻... 专业透视!扑克之星辅助,微乐麻辣自建房辅助视频,妙计教程(的确有挂)-哔哩哔哩1、实时扑克之星辅助透...
了解透视!hhpoker怎么开... 了解透视!hhpoker怎么开透视,微乐游戏辅助脚本安卓,方式教程(有挂讲解)-哔哩哔哩1、hhpo...
科普透视!wpk辅助哪里买,微... 科普透视!wpk辅助哪里买,微乐家乡官方app,技法教程(有挂教程)-哔哩哔哩1.wpk辅助哪里买 ...
分享透视!德州局透视,微信微乐... 分享透视!德州局透视,微信微乐游戏有辅助吗,练习教程(确实有挂)-哔哩哔哩1、下载好德州局透视正确养...
揭露透视!we-poker软件... 揭露透视!we-poker软件,陕西微乐小程序脚本,妙计教程(发现有挂)-哔哩哔哩we-poker软...
揭露透视!hhpoker软件可... 揭露透视!hhpoker软件可以玩吗,微乐小程序辅助器,积累教程(有挂头条)-哔哩哔哩1、hhpok...
关于透视!hhpoker开挂教... 您好,hhpoker开挂教程这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】...
详情透视!werplan怎么作... 详情透视!werplan怎么作弊,微乐自建房脚本入口,烘培教程(真实有挂)-哔哩哔哩1、下载好wer...
推荐透视!wepoker有辅助... 推荐透视!wepoker有辅助插件吗,微乐自建房辅助下载,讲义教程(有挂教程)-哔哩哔哩wepoke...