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

相关内容

热门资讯

交流学习经验辅助器!博达棋牌辅... 交流学习经验辅助器!博达棋牌辅助器多功能AI方法,博达棋牌切实存在有辅助器方法1、博达棋牌透视辅助软...
揭秘攻略作弊器!雀神互娱作弊器... 揭秘攻略作弊器!雀神互娱作弊器多功能AI教程,雀神互娱果然是有作弊器教程1、进入游戏-大厅左侧-新手...
交流学习经验作弊器!魔龙作弊器... 交流学习经验作弊器!魔龙作弊器多功能AI工具,魔龙原来真的是有作弊器工具小薇(辅助器软件下载)致您一...
实测分享辅助!新天地辅助多功能... 实测分享辅助!新天地辅助多功能AI技巧,新天地确实有辅助技巧1、不需要AI权限,帮助你快速的进行新天...
总算了解透视挂!豪发娱乐透视挂... 总算了解透视挂!豪发娱乐透视挂多功能AI插件,豪发娱乐一直是真的有透视挂插件1、任何豪发娱乐透视是真...
终于知道透视挂!新漫游透视挂多... 终于知道透视挂!新漫游透视挂多功能AI工具,新漫游其实存在有透视挂工具1)新漫游辅助插件:进一步探索...
科普作弊器!起点大厅作弊器多功... 科普作弊器!起点大厅作弊器多功能AI技巧,起点大厅都是存在有作弊器技巧科普作弊器!起点大厅作弊器多功...
2分钟细说辅助器!淮滨互娱辅助... 2分钟细说辅助器!淮滨互娱辅助器多功能AI工具,淮滨互娱好像存在有辅助器工具1、超多福利:超高返利,...
科普分享外挂!918娱乐外挂多... 科普分享外挂!918娱乐外挂多功能AI方法,918娱乐一贯有外挂方法1、实时918娱乐透视辅助更新:...
实测必看外挂!54棋牌外挂多功... 实测必看外挂!54棋牌外挂多功能AI技巧,54棋牌总是真的有外挂技巧暗藏猫腻,小编详细说明54棋牌破...