Android O - 单行通知 - 像 "Android System - USB charging this device"

标签 android android-notifications android-8.0-oreo

我想收到我的 ForegroundService 的持续通知这需要尽可能小的地方。我喜欢“Android 系统 - USB 充电此设备”风格,但我找不到任何示例如何实现这一点。
enter image description here
谁能指出我正确的方向?
更新
如果 channel 被分配了重要性 IMPORTANCE_MIN,则为通知提供样式.
看起来没有办法使用内置样式的 Android 来通知 IMPORTANCE_MINForegroundService 一起使用.
这是IMPORTANCE_MIN的描述:

Min notification importance: only shows in the shade, below the fold. This should not be used with Service.startForeground since a foreground service is supposed to be something the user cares about so it does not make semantic sense to mark its notification as minimum importance. If you do this as of Android version Build.VERSION_CODES.O, the system will show a higher-priority notification about your app running in the background.

最佳答案

要显示类似于收费通知的紧凑单行通知,您必须创建 Notification Channel优先于 IMPORTANCE_MIN。

@TargetApi(Build.VERSION_CODES.O)
private static void createFgServiceChannel(Context context) {
   NotificationChannel channel = new NotificationChannel("channel_id", "Channel Name", NotificationManager.IMPORTANCE_MIN);
   NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
   mNotificationManager.createNotificationChannel(channel);
}

然后像这样创建一个持续的通知:
public static Notification getServiceNotification(Context context) {
   NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, "channel_id");
   mBuilder.setContentTitle("One line text");
   mBuilder.setSmallIcon(R.drawable.ic_notification);
   mBuilder.setProgress(0, 0, true);
   mBuilder.setOngoing(true);
   return mBuilder.build();
}

注意

请注意,我已经使用 IntentService 对其进行了测试。而不是 Service ,并且有效。另外我刚刚检查了设置 Thread.sleep() 15 秒,通知完美显示,直到 IntentService自行停止。

有一些图片(抱歉有些文字是西类牙语,但我认为这些图片仍然有用):

Single line ongoing notification

如果你向下拖动并打开通知,它会显示如下:

Single line ongoing notification opened

额外

如果您注意到 Android 系统显示一个通知,指示所有正在使用电池的应用程序(具有持续服务的应用程序),您可以降低此类通知的优先级,它将像充电通知一样显示为一行通知。

看看这个:

Battery applications

只需长按此通知,然后选择所有类别:

Chennel notification for battery applications

并将重要性设置为 LOW:

enter image description here

下次,这个“电池消耗”通知将显示为充电通知。

关于Android O - 单行通知 - 像 "Android System - USB charging this device",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60216294/

相关文章:

android - 在 JobIntentService onComplete 上崩溃

Android 交互通知

android - 绘制背景RelativeLayout时出现NullPointerException

android - 我想在 android 中将音频服务器 (/frameworks/av/media/audioserver) 构建为 64 位,但它无法启动

android - 无法获取刚刚创建的文件的 DriveID 和 ResourceID

android - 我怎样才能从一个方法触发我的通知?

Android - 将事件通知传递给可能不活跃的 Activity 的有效方法?

Android O : Service. stopForeground 等效

android - SurfaceView 在 Android 8.0 上与另一个 SurfaceView 重叠

android - 测试两个设备之间的交互(通过 Espresso)