我有问题。我的服务起作用了,但当我关闭应用程序时,服务停止了。如何让我的服务处于运行状态?
服务
[Service]
public class NotificationService : Service
{
public NotificationService () { }
public override StartCommandResult OnStartCommand (Android.Content.Intent intent, StartCommandFlags flags, int startId)
{
new Task(() =>
{
DoWork();
} ).Start();
return StartCommandResult.Sticky;
}
public override void OnDestroy ()
{
base.OnDestroy ();
}
public override IBinder OnBind (Intent intent)
{
throw new NotImplementedException ();
}
void DoWork()
{
new Task(() =>
{
for (int i = 0; i < 100; i ++)
{
System.Threading.Thread.Sleep(1000);
var context = Android.App.Application.Context;
var builder = new Android.App.Notification.Builder(context)
.SetSmallIcon(Resource.Drawable.icon)
.SetContentTitle("My application")
.SetDefaults(NotificationDefaults.Sound)
.SetContentText(i.ToString())
.SetOngoing(true);
var not = builder.Build();
var notManager = context.GetSystemService(NotificationService) as NotificationManager;
notManager.Notify(1, not);
}
}).Start();
}
}
MainActivity.cs
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
global::Xamarin.Forms.Forms.Init (this, bundle);
LoadApplication (new App ());
new Task(() =>
{
var notificationIntent = new Intent(this, typeof(NotificationService));
StartService(notificationIntent);
}).Start();
Android.Widget.Toast.MakeText(this, "run", Android.Widget.ToastLength.Short).Show();
}发布于 2019-08-13 19:45:38
当我们从VS启动应用程序并停止应用程序时。VS自动关闭所有服务。需要建立应用程序到设备,然后从设备启动应用程序。
发布于 2021-06-14 19:30:39
很抱歉回答得太晚了,但我认为这对其他人有帮助。我想向您说明一点,您正在编写此服务作为后台服务。后台服务无法长时间运行。Android 8.0及以上版本的Android后台服务存在一定的局限性。Android会在一段时间后自动关闭应用的后台服务。
查看此https://developer.android.com/about/versions/oreo/background
如果你想长时间运行一个服务,那么就让这个服务成为前台服务。请关注https://docs.microsoft.com/en-us/xamarin/android/app-fundamentals/services/foreground-services以Xamarin形式获取前台服务的详细知识。
https://stackoverflow.com/questions/33605912
复制相似问题