簡體   English   中英

Xamarin 表單中的后台服務

[英]Background Service in Xamarin Forms

我在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!");                        

                }
            });
        });

    }

這里的主要問題是我的定期服務除了第一次之外沒有發送任何消息。 通知只顯示一次! 請幫忙。

創建一個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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM