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

相关内容

热门资讯

透视有挂!wepoker免费脚... 透视有挂!wepoker免费脚本,poker world辅助器,绝活儿教程(本来真的是有挂)-哔哩哔...
透视肯定!aapoker破解侠... 透视肯定!aapoker破解侠是真的吗,wepoker私人局怎么玩,方式教程(总是是有挂)-哔哩哔哩...
透视插件!来玩app 德州 辅... 透视插件!来玩app 德州 辅助,约局吧如何查看是否有挂,教程书教程(一贯是有挂)-哔哩哔哩一、约局...
透视辅助!wepoker软件辅... 透视辅助!wepoker软件辅助程序,wepoker辅助器下载,总结教程(原来存在有挂)-哔哩哔哩1...
透视插件!wepoker如何设... 透视插件!wepoker如何设置透视,wepoker私人局俱乐部怎么进,手筋教程(真是真的是有挂)-...
透视安卓版!we poker辅... 透视安卓版!we poker辅助器,约局吧怎么看有没有挂,绝活儿教程(果然是真的挂)-哔哩哔哩1、让...
透视透视!hardrock透视... 透视透视!hardrock透视工具,poker master辅助,资料教程(都是存在有挂)-哔哩哔哩...
透视苹果版!wepoker黑侠... 透视苹果版!wepoker黑侠辅助器,sohoo开挂辅助,要领教程(真是有挂)-哔哩哔哩1、不需要A...
透视挂!wepoker私人局辅... 您好,wepoker私人局辅助挂这款游戏可以开挂的,确实是有挂的,需要了解加去威信【13670430...
透视新版!wepoker辅助方... 透视新版!wepoker辅助方法,hhpoker开挂教程,技法教程(一直是有挂)-哔哩哔哩1、每一步...