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多开辅助器手段!德普之星私人局辅助器,红龙PoKerai多功能辅助器教程1、下载好德普之星私人...
玩家爆料辅助器!四川家园ai辅... 您好,四川家园这款游戏可以开挂的,确实是有挂的,需要了解加微【485275054】很多玩家在这款游戏...
WPK透视辅助器阶段!wepo... WPK透视辅助器阶段!wepoker私人局开挂视频,WePoKerai多功能辅助器工具1、任何wep...
推荐一款开挂!奉化同乡游麻将a... AI 黑科技赛道又上新,这款智能处理工具堪称效率开挂,专门面向短视频创作者打造。它打通脚本撰写、AI...
WPK透视版透视项目!微扑克透... WPK透视版透视项目!微扑克透视脚本,德扑之星ai多功能透视方法微扑克透视脚本辅助器是一种具有地方特...
热点推荐透视挂!闲娱麻将ai透... 热点推荐透视挂!闲娱麻将ai透视挂多功能插件,果然是真的有透视挂脚本妙招是一款可以让一直输的玩家,快...
WPK插件透视积累!wepok... WPK插件透视积累!wepoker亲友圈有用吗,微扑克ai多功能透视神器1.wepoker亲友圈有用...
新手必备辅助!大宝苏北麻将ai... 您好,大宝苏北麻将这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家在这款...
WPK购买辅助器练习!wepo... WPK购买辅助器练习!wepoker代打辅助,WePoKerai多功能辅助器技巧1、下载好wepok...
让我来分享经验辅助挂!山西大唐... 您好:山西大唐这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特别好,...