2017-08-30 124 views
0

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

       } 
      }); 
     }); 

    } 

這裏的主要問題是我的定期服務除第一次以外不發送任何消息。該通知只顯示一次!請幫忙。

+1

您:

[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); } } 

使用掛起的意圖是 「呼叫」 你IntentService然後使用AlarmManager設置重複報警在您的服務中只調用一次** MessagingCenter.Send ** ** – SushiHangover

+0

@SushiHangover謝謝您的回答。那麼我怎樣才能每隔n小時發送一次該通知? – Subash

+1

通過AlarmManager/SetRepeating使用重複警報是計劃重新發生事件的更好方法,請參閱我的答案:https://stackoverflow.com/a/45657600/4984832 – SushiHangover

回答

2

創建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); 
} 
+0

我相信這可行,但請多一點幫助,我如何在每天上午10點,下午2點和下午5點設置通知?此外,如果設備在此時關閉,我需要稍後發送通知。 – Subash

+0

謝謝,我將此標記爲答案,並且我找到了解決我的問題的方法:) – Subash