4.9

安卓通知系统与富媒体推送
安卓通知系统为应用与用户提供了重要的交互渠道,特别是在后台服务场景中。以下是 Java 实现的关键技术点:

  1. 创建通知渠道(Android 8.0+)
    java
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    NotificationChannel channel = new NotificationChannel(
    "channel_id",
    "Channel Name",
    NotificationManager.IMPORTANCE_DEFAULT
    );
    channel.setDescription("Channel Description");
    NotificationManager manager = getSystemService(NotificationManager.class);
    manager.createNotificationChannel(channel);
    }
  2. 构建富媒体通知
    java
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "channel_id")
    .setSmallIcon(R.drawable.ic_notification)
    .setContentTitle("New Message")
    .setContentText("You have a new message")
    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
    .setStyle(new NotificationCompat.BigPictureStyle()
    .bigPicture(BitmapFactory.decodeResource(getResources(), R.drawable.big_image)))
    .setAutoCancel(true);

NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(notificationId, builder.build());
3. 处理通知点击事件
java
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);

builder.setContentIntent(pendingIntent);

posted @ 2025-04-09 21:51  Echosssss  阅读(7)  评论(0)    收藏  举报