0

0

解决Android 13+ FCM数据消息通知不显示问题:运行时权限与最佳实践

聖光之護

聖光之護

发布时间:2025-07-09 18:26:15

|

981人浏览过

|

来源于php中文网

原创

解决Android 13+ FCM数据消息通知不显示问题:运行时权限与最佳实践

本教程详细探讨了在Android 13及更高版本中,FCM(Firebase Cloud Messaging)数据消息虽已成功接收但系统通知不显示的问题。核心原因在于Android 13引入的通知运行时权限。文章将提供从权限声明到运行时请求的完整解决方案,并结合实际代码示例,指导开发者确保FCM数据消息能够正确地在用户设备上显示为本地通知,同时涵盖Android通知系统的其他关键配置,如通知渠道。

FCM数据消息与本地通知的挑战

firebase cloud messaging (fcm) 提供了两种主要的消息类型:通知消息(notification message)和数据消息(data message)。当应用需要完全控制通知的显示方式、处理自定义数据或在应用处于前台时接收消息时,通常会选择发送数据消息。数据消息的特点是,无论应用处于前台、后台还是被杀死,都会触发firebasemessagingservice中的onmessagereceived()回调方法。

开发者通常会在onMessageReceived()方法中解析收到的数据,并使用Android的NotificationManager和NotificationCompat.Builder来构建并显示一个本地通知。以下是常见的实现模式:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        // 确保收到的是数据消息,并从getData()中解析
        if (remoteMessage.getData().size() > 0) {
            String notificationTitle = remoteMessage.getData().get("title");
            String notificationBody = remoteMessage.getData().get("body");
            String clickAction = remoteMessage.getData().get("click_action"); // 示例自定义字段

            Log.d("FCM_Debug", "Notification Data: " + notificationTitle + " " + notificationBody + " " + clickAction);

            // 调用方法显示本地通知
            sendLocalNotification(notificationTitle, notificationBody, clickAction);
        }
    }

    private void sendLocalNotification(String notificationTitle, String notificationBody, String url) {
        NotificationCompat.Builder notificationBuilder;
        // 定义通知点击行为:如果url为空或空字符串,则打开应用主界面;否则,打开指定URL
        if (url == null || url.length() == 0) {
            Intent intent = new Intent(this, record_viewer.class); // 示例:打开应用内某个Activity
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE); // FLAG_IMMUTABLE 是Android 12+必需
            Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            notificationBuilder = new NotificationCompat.Builder(this, "CHANNEL_ID") // 确保使用有效的CHANNEL_ID
                    .setAutoCancel(true)
                    .setSmallIcon(R.mipmap.ic_launcher) // 确保图标存在且为有效资源ID
                    .setContentIntent(pendingIntent)
                    .setContentTitle(notificationTitle)
                    .setContentText(notificationBody)
                    .setSound(defaultSoundUri);
        } else {
            Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
            notificationIntent.setData(Uri.parse(url));
            PendingIntent pending = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE);
            Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            notificationBuilder = new NotificationCompat.Builder(this, "CHANNEL_ID") // 确保使用有效的CHANNEL_ID
                    .setAutoCancel(true)
                    .setSmallIcon(R.drawable.download_icon) // 确保图标存在且为有效资源ID
                    .setContentIntent(pending)
                    .setContentTitle(notificationTitle)
                    .setContentText(notificationBody)
                    .setSound(defaultSoundUri);
        }

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(1234, notificationBuilder.build());
    }
}

尽管日志显示数据已成功接收,但用户却无法在设备上看到通知。这通常是由于Android系统对通知显示权限的收紧所致。

Android 13 (API 33) 通知运行时权限

从Android 13 (API 级别 33) 开始,Google引入了一项新的运行时权限:POST_NOTIFICATIONS。这意味着应用在向用户显示通知之前,必须明确请求并获得此权限。如果应用的目标SDK版本为33或更高,并且未获得此权限,那么即使调用NotificationManager.notify(),通知也不会显示给用户。

这是为了给用户更多的控制权,允许他们决定哪些应用可以发送通知,从而减少不必要的干扰。

解决方案:权限声明与运行时请求

解决FCM数据消息无法显示本地通知的问题,需要以下两个步骤:

1. 在 AndroidManifest.xml 中声明权限

首先,在应用的AndroidManifest.xml文件中声明POST_NOTIFICATIONS权限。这是所有Android版本都需要的,但对于API 33及以上版本,它会触发运行时权限请求。



    
     

    
        
            
                
            
        
        
    

2. 在运行时请求权限(针对 Android 13+)

对于目标SDK版本为33或更高的应用,在尝试显示通知之前,必须在用户界面中适当地请求POST_NOTIFICATIONS权限。这通常在应用的启动流程中,或在用户首次需要接收通知功能时进行。

有道智云AI开放平台
有道智云AI开放平台

有道智云AI开放平台

下载

推荐使用ActivityResultLauncher来处理权限请求的回调:

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

public class MainActivity extends AppCompatActivity {

    // 用于处理权限请求结果的Launcher
    private final ActivityResultLauncher requestPermissionLauncher =
            registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
                if (isGranted) {
                    // 权限已授予。现在可以显示通知了。
                    Log.d("Permission", "Notification permission granted.");
                    // 如果有待处理的通知,可以在这里尝试重新显示
                } else {
                    // 权限被拒绝。通知用户或禁用相关通知功能。
                    Log.d("Permission", "Notification permission denied.");
                    // 可以引导用户去设置中手动开启
                }
            });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 在合适的时机调用此方法请求通知权限
        requestNotificationPermission();
    }

    private void requestNotificationPermission() {
        // 仅在Android 13 (API 33) 及更高版本上才需要运行时请求
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) ==
                    PackageManager.PERMISSION_GRANTED) {
                // 权限已授予,无需再次请求
                Log.d("Permission", "Notification permission already granted.");
            } else if (shouldShowRequestPermissionRationale(Manifest.permission.POST_NOTIFICATIONS)) {
                // 如果用户之前拒绝过但没有勾选“不再询问”,则显示一个解释性UI
                // 解释为什么应用需要此权限,然后再次请求
                Log.d("Permission", "Should show permission rationale for notifications.");
                // 可以在这里显示一个AlertDialog,解释原因,然后调用requestPermissionLauncher.launch()
                requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS);
            } else {
                // 直接请求权限
                Log.d("Permission", "Requesting notification permission directly.");
                requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS);
            }
        }
    }
}

注意事项:

  • API 版本检查: 务必使用Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU来判断当前设备是否为Android 13或更高版本。低于此版本的设备不需要运行时请求此权限。
  • 请求时机: 选择一个合适的时机请求权限,例如在应用首次启动时,或者当用户点击某个需要通知功能按钮时。避免在应用启动时立即强制请求,这可能会影响用户体验。
  • 用户体验: 如果shouldShowRequestPermissionRationale()返回true,这意味着用户之前拒绝过权限但没有选择“不再询问”。此时,最好向用户解释为什么应用需要通知权限,这有助于提高用户授权的意愿。

完善本地通知逻辑:通知渠道 (Android 8.0+)

虽然不是FCM数据消息不显示通知的直接原因,但从Android 8.0 (API 26) 开始,所有通知都必须分配到一个通知渠道 (Notification Channel)。如果没有为通知指定渠道,或者指定的渠道无效,通知将不会显示。这是一个常见的遗漏点,也可能导致通知不显示。

在sendLocalNotification方法中,确保在构建NotificationCompat.Builder之前创建并注册了通知渠道。通知渠道只需创建一次,通常在Application类的onCreate方法中,或在首次显示通知时调用。

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;
// ... 其他导入

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String CHANNEL_ID = "my_app_notification_channel"; // 定义一个唯一的渠道ID
    private static final CharSequence CHANNEL_NAME = "通用通知"; // 用户可见的渠道名称
    private static final String CHANNEL_DESCRIPTION = "此渠道用于接收应用的重要通知"; // 用户可见的渠道描述

    @Override
    public void onCreate() {
        super.onCreate();
        createNotificationChannel(); // 在服务创建时创建通知渠道
    }

    private void createNotificationChannel() {
        // 仅在Android 8.0 (API 26) 及更高版本上需要通知渠道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_DEFAULT; // 通知重要性级别
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, importance);
            channel.setDescription(CHANNEL_DESCRIPTION);
            // 将渠道注册到系统
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
        }
    }

    private void sendLocalNotification(String notificationTitle, String notificationBody, String url) {
        // ... (省略部分代码,与之前相同)

        NotificationCompat.Builder notificationBuilder;
        if (url == null || url.length() == 0) {
            // ... (省略部分代码)
            notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID) // 确保使用定义的CHANNEL_ID
                    .setAutoCancel(true)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentIntent(pendingIntent)
                    .setContentTitle(notificationTitle)
                    .setContentText(notificationBody)
                    .setSound(defaultSoundUri);
        } else {
            // ... (省略部分代码)
            notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID) // 确保使用定义的CHANNEL_ID
                    .setAutoCancel(true)
                    .setSmallIcon(R.drawable.download_icon)
                    .setContentIntent(pending)
                    .setContentTitle(notificationTitle)
                    .setContentText(notificationBody)
                    .setSound(defaultSoundUri);
        }

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(1234, notificationBuilder.build());
    }
}

确保NotificationCompat.Builder的构造函数中传入了正确的CHANNEL_ID。

总结与注意事项

  1. 权限是关键: 对于Android 13 (API 33) 及更高版本,POST_NOTIFICATIONS运行时权限是FCM数据消息显示本地通知的必要条件。务必在AndroidManifest.xml中声明,并在运行时向用户请求。
  2. 渠道不可少: 对于Android 8.0 (API 26) 及更高版本,所有通知都必须关联到有效的通知渠道。确保您的应用正确创建并使用了通知渠道。
  3. 版本兼容性: 编写代码时,始终考虑不同Android版本的差异。使用Build.VERSION.SDK_INT进行条件判断,以确保在旧版本系统上不执行不必要的操作,在新版本系统上遵循新规范。
  4. 用户体验: 在请求敏感权限(如通知权限)时,提供清晰的解释,帮助用户理解为何需要此权限,可以显著提高用户授权的意愿。
  5. FCM消息类型: 本教程主要针对FCM“数据消息”的情况。如果您发送的是FCM“通知消息”,当应用处于后台或被杀死时,FCM SDK可能会自动处理并显示通知,无需您手动在onMessageReceived中创建本地通知。只有当应用处于前台时,通知消息才会触发onMessageReceived。

通过遵循上述步骤和最佳实践,您可以确保您的FCM数据消息在各种Android版本和设备上都能可靠地显示为本地通知,从而提供一致且高效的用户体验。

相关专题

更多
pdf怎么转换成xml格式
pdf怎么转换成xml格式

将 pdf 转换为 xml 的方法:1. 使用在线转换器;2. 使用桌面软件(如 adobe acrobat、itext);3. 使用命令行工具(如 pdftoxml)。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

1852

2024.04.01

xml怎么变成word
xml怎么变成word

步骤:1. 导入 xml 文件;2. 选择 xml 结构;3. 映射 xml 元素到 word 元素;4. 生成 word 文档。提示:确保 xml 文件结构良好,并预览 word 文档以验证转换是否成功。想了解更多xml的相关内容,可以阅读本专题下面的文章。

2080

2024.08.01

xml是什么格式的文件
xml是什么格式的文件

xml是一种纯文本格式的文件。xml指的是可扩展标记语言,标准通用标记语言的子集,是一种用于标记电子文件使其具有结构性的标记语言。想了解更多相关的内容,可阅读本专题下面的相关文章。

923

2024.11.28

Golang channel原理
Golang channel原理

本专题整合了Golang channel通信相关介绍,阅读专题下面的文章了解更多详细内容。

239

2025.11.14

golang channel相关教程
golang channel相关教程

本专题整合了golang处理channel相关教程,阅读专题下面的文章了解更多详细内容。

320

2025.11.17

android开发三大框架
android开发三大框架

android开发三大框架是XUtil框架、volley框架、ImageLoader框架。本专题为大家提供android开发三大框架相关的各种文章、以及下载和课程。

251

2023.08.14

android是什么系统
android是什么系统

Android是一种功能强大、灵活可定制、应用丰富、多任务处理能力强、兼容性好、网络连接能力强的操作系统。本专题为大家提供android相关的文章、下载、课程内容,供大家免费下载体验。

1720

2023.08.22

android权限限制怎么解开
android权限限制怎么解开

android权限限制可以使用Root权限、第三方权限管理应用程序、ADB命令和Xposed框架解开。详细介绍:1、Root权限,通过获取Root权限,用户可以解锁所有权限,并对系统进行自定义和修改;2、第三方权限管理应用程序,用户可以轻松地控制和管理应用程序的权限;3、ADB命令,用户可以在设备上执行各种操作,包括解锁权限;4、Xposed框架,用户可以在不修改系统文件的情况下修改应用程序的行为和权限。

1945

2023.09.19

php源码安装教程大全
php源码安装教程大全

本专题整合了php源码安装教程,阅读专题下面的文章了解更多详细内容。

7

2025.12.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
10分钟--Midjourney创作自己的漫画
10分钟--Midjourney创作自己的漫画

共1课时 | 0.1万人学习

Midjourney 关键词系列整合
Midjourney 关键词系列整合

共13课时 | 0.9万人学习

AI绘画教程
AI绘画教程

共2课时 | 0.2万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号