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

相关内容

热门资讯

重大消息!欢乐对决辅助软件(辅... 重大消息!欢乐对决辅助软件(辅助挂)werplan辅助软件(其实是真的有挂);大家肯定在之前欢乐对决...
推荐一款!途游小程序辅助器(辅... 推荐一款!途游小程序辅助器(辅助挂)德普之星的辅助工具介绍(好像存在有挂)是一款可以让一直输的玩家,...
重大发现!广东闲来辅助神器免费... 重大发现!广东闲来辅助神器免费版(辅助挂)wpk辅助购买(好像是有挂);AI辅助机器人普及解说快速成...
科技新动态!四川途游小程序辅助... 科技新动态!四川途游小程序辅助软件(辅助挂)红龙poker作弊指令(从前真的有挂)是一款可以让一直输...
一分钟教你!桂麻圈辅助(辅助挂... 一分钟教你!桂麻圈辅助(辅助挂)hhpoker透视脚本视频(往昔存在有挂)是一款可以让一直输的玩家,...
推荐一款!新超圣辅助靠谱不(辅... 推荐一款!新超圣辅助靠谱不(辅助挂)大菠萝免费辅助器(好像存在有挂);新超圣辅助靠谱不中的10万兆豆...
普及知识!爱游辅助app(辅助... 《普及知识!爱游辅助app(辅助挂)steampokermaster辅助(确实有挂)》 爱游辅助ap...
重大科普!老友广东插件软件(辅... 重大科普!老友广东插件软件(辅助挂)hhpoker是真的吗(好像有挂)是一款可以让一直输的玩家,快速...
玩家亲测!牵手辅助神器下载(辅... 玩家亲测!牵手辅助神器下载(辅助挂)竞技联盟透视(原生是真的有挂);牵手辅助神器下载最新软件透明挂直...