use*_*298 1 c# android push-notification xamarin.forms messagingcenter
我尝试按照此处的说明在通知点击上添加 MessagingCenter 订阅操作,以打开特定视图。我的发送/订阅在某个地方没有互相交谈,我只是看不到在哪里。消息中心的细节对我来说仍然是新的,所以我确信我只是在某个地方使用了错误的类或发送者。
下面的代码已根据链接中向我显示的内容进行了修改。但这个想法仍然大致相同。
这是我的FirebaseService类中的SendLocalNotification方法:
void SendLocalNotification(string body)
{
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.SingleTop);
intent.PutExtra("OpenPage", "SomePage");
//Unique request code to avoid PendingIntent collision.
var requestCode = new Random().Next();
var pendingIntent = PendingIntent.GetActivity(this, requestCode, intent, PendingIntentFlags.OneShot);
var notificationBuilder = new NotificationCompat.Builder(this)
.SetContentTitle("Load Match")
.SetSmallIcon(Resource.Drawable.laundry_basket_icon_15875)
.SetContentText(body)
.SetAutoCancel(true)
.SetShowWhen(false)
.SetContentIntent(pendingIntent);
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
notificationBuilder.SetChannelId(AppConstants.NotificationChannelName);
}
var notificationManager = NotificationManager.FromContext(this);
notificationManager.Notify(0, notificationBuilder.Build());
}
Run Code Online (Sandbox Code Playgroud)
这是android MainActivity中的OnNewIntent方法:
protected override void OnNewIntent(Intent intent)
{
if (intent.HasExtra("OpenPage"))
{
MessagingCenter.Send(this, "Notification");
}
base.OnNewIntent(intent);
}
Run Code Online (Sandbox Code Playgroud)
这是我尝试在LoadsPageViewModel中订阅消息的地方(而不是在 android 项目中):
public LoadsPageViewModel()
{
MessagingCenter.Subscribe<LoadsPageViewModel>(this, "Notification", (sender) =>
{
// navigate to a view here
});
}
Run Code Online (Sandbox Code Playgroud)
pin*_*dax 11
为了使其MessagingCenter工作,您需要在发送者和订阅者上使用相同的类型/对象。
由于您是从 Android 项目发送,因此this您在此处使用的值:
MessagingCenter.Send(this, "Notification");
Run Code Online (Sandbox Code Playgroud)
代表MainActivity。
当您在 ViewModel 中订阅时,您正在使用 ViewModel 对象
MessagingCenter.Subscribe<LoadsPageViewModel>(this, "Notification", (sender) => { });
Run Code Online (Sandbox Code Playgroud)
这就是为什么您没有收到对方消息的原因。
为了使其工作,您需要更改以下内容:
在 Android 主活动中,使用 Xamarin.Forms.Application 类:
MessagingCenter.Send(Xamarin.Forms.Application.Current, "Notification");
Run Code Online (Sandbox Code Playgroud)
在您的 ViewModel 中使用相同的 Xamarin.Forms.Application 类和对象:
MessagingCenter.Subscribe<Xamarin.Forms.Application>(Xamarin.Forms.Application.Current, "Notification", (sender) =>
{
Console.WriteLine("Received Notification...");
});
Run Code Online (Sandbox Code Playgroud)
这样你就会遵守所MessagagingCenter期望的。
希望这可以帮助。-
| 归档时间: |
|
| 查看次数: |
2398 次 |
| 最近记录: |