1

我有一个应用程序可以接收 FCM 通知。应用程序在 Android oreo 设备下方的操作系统上收到通知。但是通知在 android oreo 设备中没有收到。它得到的不是通知,而是“开发人员警告包未能在频道 null 上发布通知”。我搜索并了解通知渠道是必需的。但我不知道在哪里添加。请给我指导。吐司出现在 8.0 模拟器上。在真实设备中什么都没有。

4

1 回答 1

6

更新:

Android 8 中引入了通知通道。在Application 类中创建通道并分配给通知管理器是很常见的。取自Google Android的示例代码。以下是步骤

步骤 1。添加一个类来扩展应用程序并在此类中创建通道 ID,如下所示。

com.sample.app.Application.java

public class AppApplication extends Application{

    public static final String CAHNNEL_ID = "default_channel_id";

    @Override
    public void onCreate() {
        super.onCreate();
        createNotificationChannel()
    }

    private void createNotificationChannel() {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = getString(R.string.channel_name);
            String description = getString(R.string.channel_description);
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            channel.setDescription(description);
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }
}

步骤 2。编辑 AndroidManifest.xml 使得

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sample.app">
    <application
        android:name="com.sample.app.AppApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar">
        ...
    </application>

</manifest>

确保属性 android:name 的值为 AppApplication 类,如上面代码中的android:name="com.sample.app.AppApplication"

步骤 3。当您在应用程序的任何位置构建通知时,请使用以下示例代码。注意新的 NotificationCompat.Builder(this, CHANNEL_ID)

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Much longer text that cannot fit one line...")
        .setStyle(new NotificationCompat.BigTextStyle()
                .bigText("Much longer text that cannot fit one line..."))
        .setPriority(NotificationCompat.PRIORITY_DEFAULT);

值得一看的文档中的附加说明,

请注意,NotificationCompat.Builder 构造函数要求您提供通道 ID。这是与 Android 8.0(API 级别 26)及更高版本兼容所必需的,但旧版本会忽略它。

所以你必须将 targetSdkVersion 设置为至少 26 才能支持它。

于 2018-07-11T08:32:10.663 回答