Oreo - 如何自定义前台服务状态栏

Oreo - how to customize the foreground service status bar

我启动了一个前台服务,该服务显示在 android 系统电池信息下的状态栏中。

是否可以自定义显示的信息(标题、潜台词、图标...)?

服务代码:代码已编辑

@Override
    public void onCreate() {
        context = this.getApplicationContext();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Intent notificationIntent = new Intent(context, CallbackTestWidgetService.class);
            PendingIntent pendingIntent =
                    PendingIntent.getActivity(context, 10, notificationIntent, 0);

            Notification notification = new Notification.Builder(context, "Test")
                    .setContentTitle("Test")
                    .setContentText("text")
                    .setContentIntent(pendingIntent)
                    .setSmallIcon(R.drawable.test)
                    .setTicker("test")
                    .build();

CharSequence name = "test";
            String description = "test";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel("10", name, importance);
            channel.setDescription("test");
            // 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);

            startForeground(10, notification);
        }

    }

您正在构建要传递给 startForeground 的通知。使用 createContentView 函数,就像您想要自定义的普通通知一样。

请注意,这仅适用于较新版本的 Android,您可能希望使用支持库中的 NotiicationCompat class 来支持版本特定的 api 差异并进行测试几个不同的模拟器 API。

您看到的是应用未发布通知时的默认通知。

没有发布通知的原因(尽管你打电话给 startForeground)是因为你的目标是 API 26 或更高,并且没有将你的通知与 notification channel 相关联。根据该页面上的说明,这会导致您的通知被完全删除:

Caution: If you target Android 8.0 (API level 26) and post a notification without specifying a notification channel, the notification does not appear and the system logs an error.

您必须创建通知渠道,然后在构建通知时包含通知渠道的 ID。