【发布时间】:2021-03-16 12:33:41
【问题描述】:
我想更新前台通知的 ContentText,以便 ContentText 显示最新产品的日期。
我使用两个全局变量来保持对原始 Builder 和 notificationManager 的引用。 UpdateNotificationContent() 是从另一个类调用的,我已将更新后的文本提供给 SetContentText 并调用 notificationManager.notify 以尝试更新构建器。
以下行(UpdateNotificationContent 的最后一行)出现错误:notificationManager.Notify(NOTIFICATION_SERVICE_ID, notificationBuilder.Build());
Java.Lang.NullPointerException: '尝试在空对象引用上调用虚拟方法'android.content.res.Resources android.content.Context.getResources()'
完整代码here.
class MyService : Service
{
private Handler handler;
private Action runnable;
private bool isStarted;
private int DELAY_BETWEEN_LOG_MESSAGES = 5000;
private int NOTIFICATION_SERVICE_ID = 1001;
private int NOTIFICATION_AlARM_ID = 1002;
private string NOTIFICATION_CHANNEL_ID = "1003";
private string NOTIFICATION_CHANNEL_NAME = "Update Notifications";
private NotificationCompat.Builder notificationBuilder;
private NotificationManager notificationManager
private void DispatchNotificationThatServiceIsRunning()
{
Intent intent = new Intent(this, typeof(CustomReceiver));
PendingIntent pendingIntent = PendingIntent.GetBroadcast(
this,
1,
intent,
PendingIntentFlags.UpdateCurrent
);
string contextText = App.latestProduct.ProductSaveTime.ToString();
}
var notification = new Notification.Builder(this, default)
.SetChannelId("location_notification")
.SetContentTitle("AppName")
.SetContentText(contextText)
.SetSmallIcon(Resource.Drawable.icon)
.SetVisibility(NotificationVisibility.Secret)
.SetContentIntent(pendingIntent)
.SetOngoing(true)
.Build();
// Enlist this instance of the service as a foreground service
StartForeground(NOTIFICATION_SERVICE_ID, notification);
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.Notify(NOTIFICATION_SERVICE_ID, notification);
}
// every 5 seconds push a notificaition
private void DispatchNotificationThatAlarmIsGenerated()
{
Intent intent = new Intent(this, typeof(CustomReceiver));
PendingIntent pendingIntent = PendingIntent.GetBroadcast(
this,
1,
intent,
PendingIntentFlags.UpdateCurrent
);
string contextText = App.latestProduct.ProductSaveTime.ToString();
notificationBuilder = new NotificationCompat.Builder(this, "default")
.SetAutoCancel(false)
.SetSmallIcon(Resource.Drawable.icon)
.SetContentIntent(pendingIntent)
.SetContentTitle("AppName")
.SetContentText(contextText);
notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.Notify(NOTIFICATION_AlARM_ID, notificationBuilder.Build());
}
public void UpdateNotificationContent()
{
string contextText = App.latestProduct.ProductSaveTime.ToString();
notificationBuilder = new NotificationCompat.Builder(this, "default")
.SetContentText(contextText);
notificationManager.Notify(NOTIFICATION_SERVICE_ID, notificationBuilder.Build());
}
}
【问题讨论】:
标签: c# android xamarin xamarin.android android-notifications