首页 > 解决方案 > 是否有任何 Android 通知 setContentTitle 和 setContextText 魔法值?

问题描述

我目前正在开发一个支持 android 的库。

我被要求在前台服务启动时通知用户。通知必须包含“ApplicationName”作为标题,“ApplicationName is running”作为文本。通知图标必须与启动器图标相同。

目标 API 级别为 26。

通知不起作用,因为之前的开发人员忘记打开通知通道。现在已修复此问题,我们有正确弹出的通知。并且标签符合预期。

但现在我质疑为什么通知包含预期值。我在 javadoc 中找不到任何参考。以下代码将按预期显示通知,将应用程序名称作为标题和文本“ApplicationName is running”:

@Override
public void onCreate() {
    NotificationChannel channel = new NotificationChannel("APPLICATION_CHANNEL", "MyService", NotificationManager.IMPORTANCE_LOW);
    channel.setDescription(notificationChannelText);
    //block below useful for head up notification
    channel.setSound(null, null);
    channel.setShowBadge(false);
    channel.enableLights(false);
    channel.enableVibration(false);

    NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.createNotificationChannel(channel);
}
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
    foregroundNotification();
    return Service.START_STICKY;
}
/**
 * In order to start foreground service we and generate a service running notification.
 */
private void foregroundNotification() {
    Context context = getApplicationContext();
    Intent notificationIntent = new Intent(context, getClass());
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
    Notification notification = new Notification.Builder(context, "APPLICATION_CHANNEL")
            .setContentTitle("Title")
            .setContentText("Subject")
            .setContentIntent(pendingIntent)
            .build();
    startForeground(42666, notification);
}

为什么它不只显示以“Title”为标题和“Subject”为内容的通知?

是否有任何我们必须知道的常数或魔法值?

我们在哪里可以找到有关它的任何文档或定义?

编辑 2020/04/01:添加了表示通知通道创建的代码

标签: androidandroid-notifications

解决方案


我发现了你的问题。这是您的代码的结果:

在此处输入图像描述

并添加小图标后:

.setSmallIcon(R.mipmap.ic_launcher)

在此处输入图像描述

它工作正常


推荐阅读