我正在为我的应用程序使用xamarin表单。我正在为我的应用程序使用前台服务以在后台工作。我杀死了该应用程序,当我尝试重新启动该应用程序时,无法打开该应用程序。在这里,我在下面添加我的服务代码。请查看代码,并给我建议以解决此问题。
我的服务代码如下: MyPrjService.cs:
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Java.Lang;
using System.Threading;
using System.Threading.Tasks;
using Android.Support.V4.App;
using Android;
using Android.Media;
using MyPrj.Interface;
using Xamarin.Forms;
using System.IO;
using Android.Net;
using MyPrj.Common;
using MyPrj.Services;
using Android.App;
using MyPrj.BusinessLogic;
using MyPrj.Helper;
using System;
using Plugin.Connectivity;
using MyPrj.Form;
using Android.Graphics;
namespace MyPrj.Droid.Services
{
[Service]
public class MyPrjService : Service
{
CancellationTokenSource _cts;
private static ILogger logger = DependencyService.Get<ILogManager>().GetLog();
public const string LOCATION_CHANNEL = "default";
NotificationManager manager;
NotificationCompat.Builder notification;
public override void OnCreate()
{
base.OnCreate();
manager = (NotificationManager)Forms.Context.GetSystemService("notification");
}
public override IBinder OnBind(Intent intent)
{
return null;
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
StartLocationServiceForeground();
return StartCommandResult.Sticky;
}
void StartLocationServiceForeground()
{
try
{
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
var chan1 = new NotificationChannel(LOCATION_CHANNEL,
new Java.Lang.String("Primary"), NotificationImportance.High);
manager.CreateNotificationChannel(chan1);
notification = new NotificationCompat.Builder(Forms.Context, LOCATION_CHANNEL);
notification.SetOngoing(true)
//.SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.icon))
.SetSmallIcon(Resource.Drawable.icon_transparent)
.SetContentTitle("MyPrj is running background")
.SetContentText("Tab for more information or to stop the app")
.SetColor(0x9c6114)
.SetPriority(NotificationCompat.PriorityHigh);
StartForeground(1, notification.Build());
}
}
catch(System.Exception ex)
{
}
}
public override void OnDestroy()
{
StopForeground(true);
if (manager!=null)
{
manager.CancelAll();
}
base.OnDestroy();
}
}
}
App.xaml.cs:
protected override async void OnSleep()
{
try
{
var context = Droid.MainActivity.Instance;
if (context != null)
{
context.StartServiceFromApp();
}
}
}
protected async override void OnResume()
{
var context = Droid.MainActivity.Instance;
if (context != null)
{
context.StopServiceFromApp();
}
}
MainActivity.cs:
public void StartServiceFromApp()
{
os 9
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
var intent1 = new Intent(this, typeof(MyPrjService));
StartService(intent1);
}
}
public void StopServiceFromApp()
{
var intent1 = new Intent(this, typeof(ScoularService));
StopService(intent1);
}