在Android O上使用`startForeground`时,不显示自定义通知

时间:2019-10-12 09:19:47

标签: android

我想运行后台位置服务。它或多或少地起作用,但是-显示通用通知,而不是我的带有文本和内容意图的自定义通知。这是为什么?

我正在使用Nexus API 28仿真器。

服务启动方法:

private void moveToRunningState() {
    Intent serviceStartIntent = new Intent(getApplicationContext(), this.getClass());
    int requestId = 1;
    Intent goToMainScreenIntent = new Intent(getApplicationContext(), MainActivity.class);
    serviceStartIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent onTapIntent = PendingIntent.getActivity(getApplicationContext(), requestId, goToMainScreenIntent, 0);

    Notification.Builder builder = NotificationUtils.notificationBuilderO(this);
    builder.setContentTitle("Location tracking is running");
    builder.setContentText("Your location is beeing sent to the server so it can be shown on map");
    builder.setFullScreenIntent(onTapIntent, true);
    builder.setProgress(0,100,true);

    if (NotificationUtils.isPreAndroidO()) {
        Log.d(TAG, "moveToStartedState: Running on Android N or lower - startService(intent)");
        startService(serviceStartIntent);
    } else {
        Log.d(TAG, "moveToStartedState: Running on Android O - startForegroundService(intent)");
        startForegroundService(serviceStartIntent);
    }

    startForeground(1, builder.build());
    Log.i(TAG, "Service moved to start state");
    isRunning = true;
}

以防万一,创建生成器

public static Notification.Builder notificationBuilderO(Context ctx) {
    NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
    NotificationChannel notificationChannel = new NotificationChannel(UUID.randomUUID().toString(), "Geoloc channel", NotificationManager.IMPORTANCE_DEFAULT);
    notificationManager.createNotificationChannel(notificationChannel);
    Notification.Builder builder = new Notification.Builder(ctx, notificationChannel.getId());
    return builder;

和实际结果:

enter image description here

1 个答案:

答案 0 :(得分:0)

和往常一样,我不得不在SO上发布问题,只是几秒钟后才找到答案。

问题是,我没有设置通知图标。我尝试使用NotificationManager显示相同的通知,但由于说明性异常,即未设置此图标而失败。在使用startForeground

的情况下,此例外未显示在日志中

总而言之,设置图标可解决此问题。