【发布时间】:2017-12-25 03:22:06
【问题描述】:
我正在做的是我在 Xamarin.Android 中创建了一个简单的服务,现在它只是发送一个本地推送通知。
在我的主应用程序 (MainActivity) 中,我做了一个检查该服务是否运行的语句。如果没有,我将简单地启动服务,否则我什么都不做。
if (UtilityController.IsServiceRunning(typeof(WidgetService), this) == false)
{
StartService(new Intent(this, typeof(WidgetService)));
}
这也很好用。这里没有问题。
现在,问题在于我的服务被多次运行。
[Service]
public class WidgetService : Service
{
public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId)
{
SendPushNotification();
return StartCommandResult.Sticky;
}
//Other functions such as OnBind, OnDestroy etc..
}
在这里,我有一项直截了当的服务。它的唯一目的是在函数SendPushNotification(); 中发送推送通知。
但是,当我使用不同的 StartCommandResult 枚举时,我的 OnStartCommand 函数会以不同的方式触发(我认为这是因为它会重新启动服务):
- 使用
StartCommandResult.Sticky会使服务在我每次关闭/杀死主应用时自行重启。 - 使用
StartCommandResult.NotSticky会使服务在我每次启动主应用程序时自行重启。
这是个问题。我希望该服务仅在它仍在运行时运行一次。除非我明确告诉它,否则我不希望它重新启动。
我如何做到这一点?
【问题讨论】:
-
Using StartCommandResult.NotSticky makes the Service restart itself every time I start the main app.除非被告知,否则服务不会自行启动/重新启动,即StartService -
@SushiHangover 显然是这样。
-
那么您在应用程序的开头调用
StartService,服务生命周期:developer.android.com/reference/android/app/…
标签: java c# android xamarin service