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

相关内容

热门资讯

玩家必备科普“wpk辅助期免费... 玩家必备科普“wpk辅助期免费版”开挂辅助软件(透视)详细教程是一款可以让一直输的玩家,快速成为一个...
推荐几款新版“wepoker到... 您好:wepoker到底能不能开挂这款游戏是可以开挂的,软件加【添加微信客服136704302】确实...
我来教大家“WePoker透视... 您好:WePoker透视插件怎么装的软件,软件加客服确实是有挂的,很多玩家在这款游戏中打牌都会发现很...
我来教教大家“wepoker能... 您好:wepoker能不能开挂透视这款游戏是可以开挂的,软件加【添加微信客服136704302】确实...
热点讨论“wepoker辅助透... 您好,wepoker辅助透视挂这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很...
大家学习交流“wepoker辅... >>>您好:,软件加微信【添加136704302】确实是有挂的,很多玩家在这款游戏中打牌都会发现很多...
今日头条“wepoker发牌规... >>>您好:,软件加微信【添加136704302】确实是有挂的,很多玩家在这款游戏中打牌都会发现很多...
实测教程“wepoker有没有... >>>您好:,软件加微信【添加136704302】确实是有挂的,很多玩家在这款游戏中打牌都会发现很多...
最新研发“wrpoker透视挂... 您好:wrpoker透视挂真的吗这款游戏是可以开挂的,软件加【添加微信客服136704302】确实是...
分享一款“wpk正版透视”开挂... 您好:wpk正版透视这款游戏是可以开挂的,软件加【添加微信客服136704302】确实是有挂的,很多...