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

相关内容

热门资讯

9分钟了解“微扑克封号如何避免... 9分钟了解“微扑克封号如何避免”开挂辅助安装(透视)安装教程是一款可以让一直输的玩家,快速成为一个“...
一分钟教会你“wepoker透... >>您好:wepoker透视挂安装软件加扣扣群确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户...
终于清楚“wepokerplu... 您好:wepokerplus德州开挂这款游戏是可以开挂的,软件加【添加微信客服136704302】确...
必看攻略“wepoker如何开... 必看攻略“wepoker如何开透视”开挂辅助软件(透视)总结教程是一款可以让一直输的玩家,快速成为一...
玩家必用“wepoker有没有... 您好:wepoker有没有辅助挂的软件,软件加客服确实是有挂的,很多玩家在这款游戏中打牌都会发现很多...
玩家必备科普“wepoker如... 您好:wepoker如何拿到好牌的软件,软件加客服确实是有挂的,很多玩家在这款游戏中打牌都会发现很多...
分享开挂内幕“微扑克辅助工具免... 无需打开直接搜索加微信客服(136704302)咨询了解微扑克辅助工具免费版辅助器目前(微信:136...
玩家实测“德州局wepoker... 玩家实测“德州局wepoker辅助挂安全吗”开挂辅助挂(透视)科技教程是一款可以让一直输的玩家,快速...
终于清楚“wpk辅助kaq66... 无需打开直接搜索加微信客服(136704302)咨询了解wpk辅助kaq665辅助器目前(微信:13...
玩家必备攻略“wepoker能... >>您好:wepoker能不能开挂透视确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特别...