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

相关内容

热门资讯

热点推荐!!赣牌圈科技,海盗来... 热点推荐!!赣牌圈科技,海盗来了辅助脚本,第三方教程(今日头条)1、下载安装好赣牌圈科技,进入游戏主...
最新技巧!!微信道游拼十辅助器... 最新技巧!!微信道游拼十辅助器,蜜瓜大厅可以装挂吗,2024教程(有挂细节);无需打开直接搜索加(薇...
让我来分享经验!宝宝吃吃吃游戏... 让我来分享经验!宝宝吃吃吃游戏辅助,兴动互娱辅助器多少钱,系统教程(真是有挂);无需打开直接搜索加薇...
普及知识!多乐小程序破解版修改... 普及知识!多乐小程序破解版修改器,贪吃蛇辅助器,透明挂教程(有挂头条)1、下载安装好多乐小程序破解版...
程序员教你!山城九九辅助,泸州... 您好:泸州大二新手攻略这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌...
今日科普!丹东约战麻将辅助器,... 今日科普!丹东约战麻将辅助器,多乐辅助器,揭秘教程(有挂规律)1、下载安装好丹东约战麻将辅助器,进入...
重磅来袭!约局吧黑科技辅助器,... 重磅来袭!约局吧黑科技辅助器,途游手游辅助,可靠教程(有挂教学)1、下载安装好约局吧黑科技辅助器,进...
玩家必看分享!嘟咪互动修改器,... 玩家必看分享!嘟咪互动修改器,新超凡软件辅助,透视教程(有挂教程)1、下载安装好嘟咪互动修改器,进入...
教程辅助!好运南通长牌辅助,樱... 教程辅助!好运南通长牌辅助,樱花之盛辅助软件,介绍教程(有挂秘笈);无需打开直接搜索加薇136704...
记者发布!聚财app辅助,宝宝... 记者发布!聚财app辅助,宝宝游戏辅助,必赢教程(有人有挂)1、下载安装好宝宝游戏辅助,进入游戏主界...