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

相关内容

热门资讯

黑科技新版(Wepoke开发)... 黑科技新版(Wepoke开发)聚星扑克本来有挂!太无语了一贯存在有挂(2025已更新)(哔哩哔哩)准...
黑科技脚本(扑克世界app)a... 黑科技脚本(扑克世界app)aapokER一贯存在有挂!太实锤了从前真的是有挂(2025已更新)(哔...
黑科技智能ai(德州之星app... 黑科技智能ai(德州之星app安卓版)AApoker素来真的有挂!太无语了往昔是有挂(2024已更新...
黑科技软件(微扑克线上)德州w... 1、黑科技软件(微扑克线上)德州wepower竟然是真的有挂!太实锤了往昔有挂(2024已更新)(哔...
黑科技玄学(Wepoke渠道)... 黑科技玄学(Wepoke渠道)wepOKE真是真的有挂!太夸张了其实是有挂(2022已更新)(哔哩哔...
黑科技教程(Wepoke安卓版... 黑科技教程(Wepoke安卓版本)wepOke最初是真的有挂!太无语了切实存在有挂(2024已更新)...
黑科技辅助(impoker德州... 黑科技辅助(impoker德州)AAPOKER原先真的是有挂!太离谱了确实有挂(2020已更新)(哔...
黑科技总结(德扑之星入池率)A... 此外,数据分析德州(德扑之星)辅助神器app还具备辅助透视行为开挂功能,通过对客户德扑之星透明挂的深...
黑科技辅助挂(哈糖大菠萝洗牌)... 黑科技辅助挂(哈糖大菠萝洗牌)wPk好像存在有挂!太嚣张了原生真的是有挂(2023已更新)(哔哩哔哩...
黑科技神器(Wepoke德州)... 黑科技神器(Wepoke德州)aapOker往昔有挂!太实锤了从来有挂(2026已更新)(哔哩哔哩)...