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

相关内容

热门资讯

透明软件!长春科乐辅助,aap... >>您好:长春科乐辅助确实是有挂的,很多玩家在这款长春科乐辅助游戏中打牌都会发现很多用户的牌特别好,...
一分钟教你!创思维激k破解更新... 一分钟教你!创思维激k破解更新内容,创乐源辅助软件(有挂开挂辅助脚本);无需打开直接搜索打开薇:13...
透明有挂!科乐填大坑辅助视频,... 透明有挂!科乐填大坑辅助视频,hhpoker真能买到挂吗-原本有挂开挂辅助工具;无需打开直接搜索微信...
重大通报!浙江游戏大厅游戏辅助... 您好:浙江游戏大厅游戏辅助器这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用...
透视好友!福建十三水辅助,po... 透视好友!福建十三水辅助,pokermaster辅助器-原先有挂开挂辅助工具;无需打开直接搜索薇:1...
一分钟了解!陕西三代二辅助器,... 您好:陕西三代二辅助器这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌...
透视辅助!微信游戏决胜游戏辅助... 透视辅助!微信游戏决胜游戏辅助,pokemmo手机版脚本免费-素来有挂开挂辅助器;无需打开直接搜索加...
终于懂了!四川乐易麻将辅助脚本... 终于懂了!四川乐易麻将辅助脚本,萍乡滚筒四幅攻略(有挂开挂辅助器);无需打开直接搜索微信(13670...
透明讲解!微信小程序免费黑科技... 微信小程序免费黑科技是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需要的用户可以加...
推荐一款!情怀游戏字牌辅助,花... 推荐一款!情怀游戏字牌辅助,花花生活圈怎么开挂(有挂开挂辅助神器);无需打开直接搜索加薇136704...