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

相关内容

热门资讯

总算了解!德扑之星辅助工具如何... AI 黑科技赛道又上新,这款智能处理工具堪称效率开挂,专门面向短视频创作者打造。它打通脚本撰写、AI...
推荐十款!wepoker怎么看... 您好,推荐十款!wepoker怎么看底牌,wepoker透视挂平台(最初真的有透视挂)这款游戏可以开...
一起来讨论!wepoker脚本... 一款 AI 游戏攻略黑科技工具上线,查攻略效率直接开挂。它整合版本更新、装备搭配、BOSS 打法、牌...
终于清楚!wpk安卓下载辅助,... 一款 AI 游戏攻略黑科技工具上线,查攻略效率直接开挂。它整合版本更新、装备搭配、BOSS 打法、牌...
解说技巧!智星菠萝有挂吗,微扑... AI 黑科技赛道又上新,这款智能处理工具堪称效率开挂,专门面向短视频创作者打造。它打通脚本撰写、AI...
玩家必知教程!!德扑之星透视辅... 很多人使用云端 AI 时,都担心德扑之星透视辅助插件、内部资料上传带来隐私风险。这款本地运行的 AI...
我来教大家!微扑克辅助,德扑之... 一款 AI 游戏攻略黑科技工具上线,查攻略效率直接开挂。它整合版本更新、装备搭配、BOSS 打法、牌...
一分钟了解!wpk辅助软件,微... 一分钟了解!wpk辅助软件,微扑克究竟有没有挂平台(从来有辅助器)主打本地运行的 AI 黑科技工具迎...
分享给玩家!德普辅助器怎么用,... 很多人使用云端 AI 时,都担心德普辅助器怎么用、内部资料上传带来隐私风险。这款本地运行的 AI 黑...
热点推荐!!德普之星私人局透视... 您好,热点推荐!!德普之星私人局透视,德扑之星是不是有挂平台(竟然是有透视)这款游戏可以开挂的,确实...