本文介绍了Android应用程式中startForeground的错误通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Xamarin Android 3.5开发服务.我们的应用程序针对Android 8.1(API 27-Oreo).我希望该服务作为前台服务运行.但是,运行服务时出现以下错误.

I am developing a service using Xamarin Android 3.5. Our app targets Android 8.1 (API 27 - Oreo). I want the service to run as a foreground service. However I am getting the following error when I run the service.

Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null pri=1 contentView=null vibrate=null sound=null defaults=0x0 flags=0x42 color=0x00000000 vis=PRIVATE)

这是该服务的代码.

public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
  base.OnStartCommand(intent, flags, startId);
  var context = Application.Context;
  const int pendingIntentId = 0;
  PendingIntent pendingIntent = PendingIntent.GetActivity(context, pendingIntentId, intent, PendingIntentFlags.OneShot);
  var notification = new NotificationCompat.Builder(context)
    .SetContentTitle("Testing")
    .SetContentText("location tracking has begun.")
    .SetSmallIcon(Resource.Drawable.icon)
    .SetContentIntent(pendingIntent)
    .SetOngoing(true)
    .Build();
    // Enlist this instance of the service as a foreground service
    const int Service_Running_Notification_ID = 935;
    StartForeground(Service_Running_Notification_ID, notification);
    return StartCommandResult.NotSticky;
}

我用以下内容更新了 AndroidManifest.xml .

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

MainActivity.c 中,我有下面的代码,我们用它来创建用于发送应用程序通知的通知通道(并正确创建了通知通道).

In the MainActivity.cs I have the follwing code which we use to create a notification channel for sending app notifications (and which correctly creates the notification channel).

private void CreateNotificationChannel()
{
  if (Build.VERSION.SdkInt < BuildVersionCodes.O)
  {
    // Notification channels are new in API 26 (and not a part of the
    // support library). There is no need to create a notification
    // channel on older versions of Android.
    return;
  }
  var channel = new NotificationChannel(ApplicationConstants.ChannelId, ApplicationConstants.ChannelName, NotificationImportance.Default)
  {
    Description = ApplicationConstants.ChannelDescription
  };
  var notificationManager = (NotificationManager)GetSystemService(NotificationService);
  notificationManager.CreateNotificationChannel(channel);
}

推荐答案

您正在创建一个通知频道,但从未在NotificationCompat.Builder中分配它:

You are creating a notification channel but never assigning it in your NotificationCompat.Builder:

var notification = new NotificationCompat.Builder(context)
   ~~~
   .SetChannelId(ApplicationConstants.ChannelId)
   ~~~

文档: https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder

这篇关于Android应用程式中startForeground的错误通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 22:12