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、用户打开应用后不用登录就可以...
2026版教学!广西友乐辅助a... 2026版教学!广西友乐辅助app"辅助辅助方法"确实确实有挂(哔哩哔哩)进入游戏-大厅左侧-新手福...
透视数据!兴动互娱怎么设置辅助... 透视数据!兴动互娱怎么设置辅助"解谜辅助器"总是是真的有挂(哔哩哔哩)1、兴动互娱怎么设置辅助辅助软...
网友热议!新道游正版开挂&qu... 网友热议!新道游正版开挂"开挂辅助方法"果然确实有挂(哔哩哔哩)新道游正版开挂透视方法中分为三种模型...
透视数据!杭州都莱辅助臁&qu... 透视数据!杭州都莱辅助臁"有挂辅助方法"切实真的有挂(哔哩哔哩)1、下载好杭州都莱辅助臁正确养号方法...
透视脚本!新二号透视辅助&qu... 透视脚本!新二号透视辅助"关于辅助插件"总是真的有挂(哔哩哔哩)1、游戏颠覆性的策略玩法,独创攻略技...
近年来!新二号辅助下载&quo... 近年来!新二号辅助下载"透视辅助方法"总是真的有挂(哔哩哔哩)1、下载好新二号辅助下载正确养号方法之...
据权威媒体报道!陕西辅助具ap... 据权威媒体报道!陕西辅助具app"辅助辅助插件"真是存在有挂(哔哩哔哩)陕西辅助具app能透视中分为...
经调查!广东闲来辅助工具&qu... 经调查!广东闲来辅助工具"曝光辅助教程"本来是有挂(哔哩哔哩)1、每一步都需要思考,不同水平的挑战广...
据玩家消息!禅游辅助"... 据玩家消息!禅游辅助"揭幕辅助挂"确实真的是有挂(哔哩哔哩)所有人都在同一条线上,像星星一样排成一排...