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

相关内容

热门资讯

详细开挂!樱花之盛牛牛挂,来来... 您好:来来拼十辅助免费下载这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户...
教会透视"有wepo... 教会透视"有wepoker透视吗"开挂(透视)辅助工具(我来教大家科技教程)教会透视"有wepoke...
推荐开挂!随意玩聚乐部辅助,雀... 【亲,雀友会钻石辅助器潮汕麻将 这款游戏可以开挂的,确实是有挂的,很多玩家在这款雀友会钻石辅助器潮汕...
推荐透视"wepok... 推荐透视"wepoker透视辅助挂的游戏特色"开挂(透视)辅助神器(最新研发专业教程)推荐透视"we...
了解辅助!新漫游大厅辅助器,枫... 您好:枫叶辅助官网下载这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌...
推荐透视"wepok... 推荐透视"wepoker透视挂方法"开挂(透视)辅助平台(必看攻略插件教程)推荐透视"wepoker...
详细辅助!椰子大厅辅助脚本,5... 详细辅助!椰子大厅辅助脚本,518互游辅助(玩家必看科普开挂辅助安装);小薇(透视辅助)致您一封信;...
原来有透视"wepo... 原来有透视"wepoker是不是有人用挂"开挂(透视)辅助挂(玩家科普黑科技教程)原来有透视"wep...
详细开挂!道游辅助脚本,川南久... 详细开挂!道游辅助脚本,川南久久辅助(玩家亲测开挂辅助脚本) >>您好:软件加薇136704302信...
盘点透视"wepok... 盘点透视"wepoker德州透视软件是真的吗"开挂(透视)辅助工具(一分钟了解必赢教程)盘点透视"w...