通知频道错误

时间:2018-07-11 08:23:38

标签: android firebase-cloud-messaging android-notifications android-8.0-oreo notification-channel

我有一个可以接收FCM通知的应用程序。该应用程序在Android Oreo设备以下的操作系统上已收到通知。但是通知未在android oreo设备中接收。它没有发出通知,而是发出了敬酒消息:“开发人员警告程序包无法在通道null上发布通知”。我搜索并了解到需要通知通道。但是我不知道要在哪里添加通知通道。请给我指导。吐司正在8.0仿真器上出现。在实际设备中什么都没有。

1 个答案:

答案 0 :(得分:4)

更新:

通知通道在Android 8中引入。通常在Application类中创建通道并将其分配给Notification Manager。来自Google Android的示例代码。以下是步骤

步骤1 。添加一个类来扩展Application并在该类中创建频道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以支持它。

相关问题