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

相关内容

热门资讯

分享个大家"龙岩闲游... 分享个大家"龙岩闲游安卓脚本"开挂(脚本)辅助脚本有挂存在-德州论坛>>您好:软件加薇1367043...
解密关于"老友辅助工... 解密关于"老友辅助工具"开挂(软件)辅助软件有挂存在-可靠技巧;无需打开直接搜索薇:13670430...
科普常识"开心泉州辅... 科普常识"开心泉州辅助"开挂(平台)辅助平台有挂技巧-扑克教程《详细加薇136704302咨询》游戏...
透视黑科技"多乐跑辅... 透视黑科技"多乐跑辅助得快"开挂(安装)辅助安装有挂方针-wpk教程>>您好:软件加薇1367043...
六分钟了解"手机游戏... 六分钟了解"手机游戏挂机辅助软件"开挂(神器)辅助神器有挂攻略-大神讲解;无需打开直接搜索加(薇:1...
科普分享"家家盘锦开... 科普分享"家家盘锦开挂"开挂(下载)辅助下载有挂技巧-大神讲解 【无需打开直接搜索加薇1367043...
玩家必看分享"新畅游... 新畅游互娱辅助是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需要的用户可以加我微信...
热点推荐"福建兄弟水... 热点推荐"福建兄弟水辅助气"开挂(神器)辅助神器新版有挂-科技教程 >>您好:软件加薇1367043...
盘点十款"潮汕来物几... 盘点十款"潮汕来物几局游戏源码"开挂(神器)辅助神器有挂分享-详细教程《详细加薇136704302咨...
实测揭晓"衢州都莱辅... 实测揭晓"衢州都莱辅助器是真的假的"开挂(透视)辅助透视有挂技巧-技巧教程【无需打开直接搜索加薇13...