You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Notification发送Android通知?现有代码问题求解决方案

Android通知代码修复方案(解决弃用方法与报错问题)

核心问题分析

  • 直接使用Notification.Builder缺乏版本兼容,API 26+强制要求通知渠道,否则通知无法显示
  • PendingIntent.getActivity的旧flag(0)在高版本API(31+)已被弃用,会触发安全警告甚至崩溃
  • 最后一行代码错误:notify()方法需要传入Notification对象,而非Notification.Builder实例,缺少.build()调用

完整修复代码

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import androidx.core.app.NotificationCompat;

// 在MainActivity的方法中调用此函数显示通知
public void showNotification() {
    // 1. 定义点击通知后跳转的Intent(示例跳转到当前Activity,可按需修改)
    Intent intent = new Intent(this, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    
    // 2. 设置适配高版本的PendingIntent标记
    int pendingIntentFlags;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        pendingIntentFlags = PendingIntent.FLAG_IMMUTABLE;
        // 若需动态修改Intent内容,改用FLAG_MUTABLE,否则推荐用IMMUTABLE保证安全性
    } else {
        pendingIntentFlags = PendingIntent.FLAG_UPDATE_CURRENT;
    }
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, pendingIntentFlags);

    // 3. 创建通知渠道(API 26+必须)
    String channelId = "default_notification_channel";
    String channelName = "默认通知渠道";
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT);
        notificationManager.createNotificationChannel(channel);
    }

    // 4. 构建兼容各版本的通知
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
            .setTicker("TickerTitle")
            .setContentTitle("Content Title")
            .setContentText("Hello how are you")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentIntent(pendingIntent)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setAutoCancel(true); // 点击通知后自动取消显示

    // 5. 发送通知
    notificationManager.notify(0, notificationBuilder.build());
}

关键修复点说明

  • 改用NotificationCompat.Builder:自动适配Android全版本,避免版本兼容问题
  • 新增通知渠道:API 26及以上系统要求所有通知必须归属渠道,否则无法正常显示
  • 更新PendingIntent标记:根据系统版本选择合规标记,消除弃用警告
  • 补充.build()调用:将Builder实例转换为Notification对象,解决原代码的报错

内容的提问来源于stack exchange,提问作者Music

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 02:47:05