我有一个Xamarin Android应用程序,并尝试发送本地通知。我有这个方法:
public void SendNotification(Context context, string message)
{
var notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
var notificationChannel = new NotificationChannel(CHANNEL_ID, Strings.ApplicationName, NotificationImportance.High);
notificationManager.CreateNotificationChannel(notificationChannel);
}
var intent = new Intent(context, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity(context, 0, intent, PendingIntentFlags.OneShot);
var bigstyle = new Notification.BigTextStyle();
bigstyle.BigText(message);
bigstyle.SetBigContentTitle(Strings.ApplicationName);
var notificationBuilder = new Notification.Builder(context)
.SetSmallIcon(Resource.Drawable.Icon) //Icon
.SetContentTitle(Strings.ApplicationName) //Title
.SetContentText(message) //Message
.SetAutoCancel(true)
.SetContentIntent(pendingIntent)
.SetStyle(bigstyle);
var notification = notificationBuilder.Build();
notificationManager.Notify(MESSAGE_TYPE_DEFAULT, notification);
}
出于测试目的,我在我的MainActivity中的On Create Method中调用了一个调用:
new NotificationService().SendNotification(this, "Test");
我最后一次测试时,是使用Android 7.0而且有效。使用Android 8.0没有抛出错误或类似的东西。我也看不到输出中的任何错误。但它只是没有显示任何通知。
8.0有什么改变或者我做错了吗?
答案 0 :(得分:2)
您必须使用Android O中的setChannelId。共享相同的java代码。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String CHANNEL_ID = getResources().getString(R.string.channel_id);// The id of the channel.
CharSequence name = getString(R.string.app_name);// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
notificationManager.createNotificationChannel(mChannel);
Notification.Builder b = new Notification.Builder(BaseActivity.this, CHANNEL_ID);
b.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.setSmallIcon(icon)
.setContentTitle(title)
.setContentText(content)
.setChannelId(CHANNEL_ID)
.setContentIntent(contentIntent);
Notification notification = b.build();
notificationManager.notify(notificationType, notification);
}
答案 1 :(得分:1)
您需要在notificationManager中添加NotificationChannel。您将在此链接中获得详细信息。 https://www.androidauthority.com/android-8-0-oreo-app-implementing-notification-channels-801097/