2017-08-30 112 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