
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) 开始,Google引入了一项新的运行时权限:POST_NOTIFICATIONS。这意味着应用在向用户显示通知之前,必须明确请求并获得此权限。如果应用的目标SDK版本为33或更高,并且未获得此权限,那么即使调用NotificationManager.notify(),通知也不会显示给用户。
这是为了给用户更多的控制权,允许他们决定哪些应用可以发送通知,从而减少不必要的干扰。
解决FCM数据消息无法显示本地通知的问题,需要以下两个步骤:
首先,在应用的AndroidManifest.xml文件中声明POST_NOTIFICATIONS权限。这是所有Android版本都需要的,但对于API 33及以上版本,它会触发运行时权限请求。
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.yourapp">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <!-- Android 13+ 通知权限 -->
<application
<!-- ... 其他应用配置 ... -->
<service
android:name=".MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<!-- ... 其他组件 ... -->
</application>
</manifest>对于目标SDK版本为33或更高的应用,在尝试显示通知之前,必须在用户界面中适当地请求POST_NOTIFICATIONS权限。这通常在应用的启动流程中,或在用户首次需要接收通知功能时进行。
推荐使用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<String> 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);
}
}
}
}注意事项:
虽然不是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。
通过遵循上述步骤和最佳实践,您可以确保您的FCM数据消息在各种Android版本和设备上都能可靠地显示为本地通知,从而提供一致且高效的用户体验。
以上就是解决Android 13+ FCM数据消息通知不显示问题:运行时权限与最佳实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号