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私人局辅助是真的吗!盘点十款辅助软件(讲解有挂)-哔哩哔哩1、wpk私人局辅助是真的...
推荐透视!德州真人透视脚本!热... 推荐透视!德州真人透视脚本!热点讨论辅助攻略(有挂秘籍)-哔哩哔哩1、上手简单,内置详细流程视频教学...
专业透视!we poker辅助... 专业透视!we poker辅助器!玩家必备教程辅助脚本(有挂头条)-哔哩哔哩1、每一步都需要思考,不...
解迷透视!德普之星app安卓版... 解迷透视!德普之星app安卓版破解版!玩家科普辅助攻略(发现有挂)-哔哩哔哩在进入德普之星app安卓...
科普透视!wepoker手机插... 科普透视!wepoker手机插件!传递经验辅助方法(果真有挂)-哔哩哔哩1、进入游戏-大厅左侧-新手...
解密透视!we poker辅助... 解密透视!we poker辅助器下载!交流学习经验辅助技巧(有挂透视)-哔哩哔哩1、进入到we po...
详情透视!红龙poker辅助器... 详情透视!红龙poker辅助器免费观看!推荐攻略辅助技巧(有挂解密)-哔哩哔哩1、红龙poker辅助...
有挂透视!wepoker好友助... 有挂透视!wepoker好友助力码!推荐十款辅助软件(确实有挂)-哔哩哔哩运wepoker好友助力码...
开挂透视!wepoker透视脚... 开挂透视!wepoker透视脚本免费使用视频!推荐攻略辅助软件(有挂工具)-哔哩哔哩;1.wepok...
分享透视!hhpoker德州透... 分享透视!hhpoker德州透视!每日必看辅助教程(有挂实锤)-哔哩哔哩1、hhpoker德州透视免...