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

相关内容

热门资讯

第6分钟了解!闲来辅助神器!其... 第6分钟了解!闲来辅助神器!其实有辅助插件(有挂头条)-哔哩哔哩1)闲来辅助神器辅助插件:进一步探索...
第2分钟了解!白金岛十胡卡辅助... 第2分钟了解!白金岛十胡卡辅助!确实真的有辅助工具(有挂细节)-哔哩哔哩1、每一步都需要思考,不同水...
第8分钟了解!锄大地小程序辅助... 第8分钟了解!锄大地小程序辅助器!原来一直总是有辅助软件(有挂教学)-哔哩哔哩1、锄大地小程序辅助器...
第1分钟了解!中至鹰潭亲友圈辅... 第1分钟了解!中至鹰潭亲友圈辅助!切实真的有辅助app(有挂总结)-哔哩哔哩1、游戏颠覆性的策略玩法...
7分钟了解!潮汕透视辅助!好像... 7分钟了解!潮汕透视辅助!好像真的是有辅助方法(有挂秘籍)-哔哩哔哩1、每一步都需要思考,不同水平的...
第二分钟了解!新道游房卡辅助器... 第二分钟了解!新道游房卡辅助器!原来是有辅助工具(发现有挂)-哔哩哔哩一、新道游房卡辅助器游戏安装教...
第9分钟了解!心悦游戏透视辅助... 第9分钟了解!心悦游戏透视辅助器!好像是有辅助脚本(有挂功能)-哔哩哔哩该软件可以轻松地帮助玩家将心...
第6分钟了解!宝宝游戏辅助器!... 第6分钟了解!宝宝游戏辅助器!确实真的是有辅助教程(有挂技巧)-哔哩哔哩1、该软件可以轻松地帮助玩家...
第八分钟了解!兴动助手辅助!好... 第八分钟了解!兴动助手辅助!好像是真的有辅助脚本(有挂细节)-哔哩哔哩1、兴动助手辅助有没有辅助教程...
5分钟了解!福建天天开心辅助器... 5分钟了解!福建天天开心辅助器是真的吗!一贯一直总是有辅助软件(确实有挂)-哔哩哔哩1、进入到福建天...