我在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!");
}
});
});
}
这里的主要问题是我的定期服务除了第一次没有发送任何消息。通知只显示一次!请帮忙。
答案 0 :(得分:2)
创建 IntentService
以发送通知:
[Service(Label = "NotificationIntentService")]
public class NotificationIntentService : IntentService
{
protected override void OnHandleIntent(Intent intent)
{
var notification = new Notification.Builder(this)
.SetSmallIcon(Android.Resource.Drawable.IcDialogInfo)
.SetContentTitle("StackOverflow")
.SetContentText("Some text.......")
.Build();
((NotificationManager)GetSystemService(NotificationService)).Notify((new Random()).Next(), notification);
}
}
然后使用 AlarmManager
设置重复警报,使用“调用”IntentService
的待处理意图:
using (var manager = (Android.App.AlarmManager)GetSystemService(AlarmService))
{
// Send a Notification in ~60 seconds and then every ~90 seconds after that....
var alarmIntent = new Intent(this, typeof(NotificationIntentService));
var pendingIntent = PendingIntent.GetService(this, 0, alarmIntent, PendingIntentFlags.CancelCurrent);
manager.SetInexactRepeating(AlarmType.RtcWakeup, 1000 * 60, 1000 * 90, pendingIntent);
}