我设法实现了我的后台服务,它非常好用。该服务连接到我的WebSocket并在应用程序关闭后保持连接活动。
当应用程序关闭时,我正在启动后台服务,以便我可以重新连接到后端,但我希望能够关闭服务,以便应用程序现在可以处理连接。
我已经尝试过标志,事件和其他条件,以便在应用启动时停止服务,但服务无论如何都会启动。
App运行时是否可以停止服务,以便App可以处理连接?
MainActivity.cs
[Activity(Label = "App",
Icon = "@drawable/ic_launcher",
Theme = "@style/splashscreen",
MainLauncher = true,
ScreenOrientation = ScreenOrientation.Portrait)]
public class MainActivity : Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
SetTheme(Resource.Style.MainTheme);
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
Forms.Init(this, bundle);
LoadApplication(new App());
StartBackgroundService();
IsAppRunning = true;
}
private void StartBackgroundService() {
StopService = false;
RealtimeService.StopServiceEventHandler += StopServiceEventHandler;
StartService(new Intent(Forms.Context, typeof(BackgroundRealtimeService)));
}
private void StopServiceEventHandler(object sender, object o) {
if (StopService) {
StopService(new Intent(Forms.Context, typeof(BackgroundRealtimeService)));
}
}
protected override void OnDestroy()
{
IsAppRunning = false;
base.OnDestroy();
}
}
}
BackgroundRealtimeService.cs
[Service]
public class BackgroundRealtimeService : Service
{
public async void Initialize() {
// Service Code
}
public override void OnCreate() {
base.OnCreate();
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) {
new Task(Initialize).Start();
return StartCommandResult.Sticky;
}
public override IBinder OnBind(Intent intent)
{
return null;
}
}
}