【发布时间】:2020-05-22 13:14:02
【问题描述】:
我在android中有一个后台服务实现为:
[Service]
public class PeriodicService : Service
{
public override IBinder OnBind(Intent intent)
{
return null;
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
base.OnStartCommand(intent, flags, startId);
// From shared code or in your PCL]
Task.Run(() => {
MessagingCenter.Send<string>(this.Class.Name, "SendNoti");
});
return StartCommandResult.Sticky;
}
}
在 MainActivity 类中:
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
UserDialogs.Init(() => (Activity)Forms.Context);
LoadApplication(new App());
StartService(new Intent(this, typeof(PeriodicService)));
}
}
在我的登录页面中的 Xamarin 表单中:
public LoginPage()
{
InitializeComponent();
int i = 0;
MessagingCenter.Subscribe<string>(this, "SendNoti", (e) =>
{
Device.BeginInvokeOnMainThread(() =>
{
i++;
CrossLocalNotifications.Current.Show("Some Text", "This is notification!");
}
});
});
}
这里的主要问题是我的定期服务除了第一次之外没有发送任何消息。通知只显示一次!请帮忙。
【问题讨论】:
-
你只在你的服务中调用
MessagingCenter.Send一次... -
@SushiHangover 谢谢你的回答。那么如何每 n 小时发送一次通知呢?
-
通过 AlarmManager/SetRepeating 使用重复警报是安排重复发生事件的更好方法,请在此处查看我的答案:stackoverflow.com/a/45657600/4984832
-
实际上,这不是警报,而是通知,所以我无法像您在答案中所做的那样发送警报。
-
您应该阅读未决意图和意图服务,警报管理器非常适合您的用例
标签: android xamarin xamarin.android xamarin.forms