Android应用程式中startForeground的错误通知

时间:2019-07-15 09:10:14

标签: android xamarin xamarin.forms xamarin.android

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

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 中,我有下面的代码,我们用它来创建用于发送应用程序通知的通知通道(并正确创建了通知通道)。

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);
}

3 个答案:

答案 0 :(得分:1)

  

无效的服务通知频道

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

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

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

答案 1 :(得分:1)

对于Xamarin.Forms和Xamarin.Android

=========将此代码置于公共替代中StartCommandResult OnStartCommand ===========

 if (Build.VERSION.SdkInt >= Build.VERSION_CODES.O)
      RegisterForegroundServiceO();
  else { RegisterForegroundService(); }

======================================== END ====== ======================

 void RegisterForegroundService()
        {
            var notification = new Notification.Builder(this)
                .SetContentTitle(Resources.GetString(Resource.String.app_name))
                .SetContentText(Resources.GetString(Resource.String.notification_text))
                .SetSmallIcon(Resource.Drawable.icon_userProfile)
                .SetContentIntent(BuildIntentToShowMainActivity())
                .SetOngoing(true)
                .Build();
            const int Service_Running_Notification_ID = 936;
            StartForeground(Service_Running_Notification_ID, notification);
        }


void RegisterForegroundServiceO()
    {
        String NOTIFICATION_CHANNEL_ID = "com.Your.project.id";
        NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Your Channel Name", NotificationManager.ImportanceHigh);

        NotificationManager manager = (NotificationManager)GetSystemService(Context.NotificationService);

        manager.CreateNotificationChannel(chan);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);

        Notification notification= notificationBuilder.SetOngoing(true)
            .SetContentTitle(Resources.GetString(Resource.String.app_name))
            .SetContentText(Resources.GetString(Resource.String.notification_text))
            .SetSmallIcon(Resource.Drawable.icon_userProfile)
            .SetContentIntent(BuildIntentToShowMainActivity())
            .SetOngoing(true)
            .Build();

        const int Service_Running_Notification_ID = 936;
        StartForeground(Service_Running_Notification_ID, notification);
    }

快乐编码。 :-)

答案 2 :(得分:0)

这是一个解决方法。

NotificationChannel chan = new NotificationChannel( "my_service_urgent", "My Channel", NotificationImportance.None );
chan.EnableVibration( false );
chan.LockscreenVisibility = NotificationVisibility.Secret;

NotificationManager notificationManager = GetSystemService( NotificationService ) as NotificationManager;
notificationManager.CreateNotificationChannel( chan );

var notification = new Notification.Builder( this, "my_service_urgent" )
    .SetContentTitle( Resources.GetString( Resource.String.app_name ) )
    .SetContentText( Resources.GetString( Resource.String.notification_text ) )
    .SetSmallIcon( Resource.Drawable.ic_stat_name )
    .SetContentIntent( BuildIntentToShowMainActivity() )
    .SetOngoing( true )
    .AddAction( BuildRestartTimerAction() )
    .AddAction( BuildStopServiceAction() )
    .Build();

// SERVICE_RUNNING_NOTIFICATION_ID = 101
// Enlist this instance of the service as a foreground service
StartForeground( Constants.SERVICE_RUNNING_NOTIFICATION_ID, notification );