пытаюсь сделать foreground service. как указано здесь:
Но, служба даже не запускается, как я поняла, что мне стоит изменить или возможно написать все заново.
В комментариях там даны несколько вариантов, например добавить атрибут [Service], если не работает. Но, когда его добавляю мне дает NullReferenceException на первой строчке в OnStartCommand в DataSource.
Что мне делать?
Я пыталась в виде теста сделать службу, которая будет записывать в файл время, а потом просто каждые две секунды выводить текст файла в label, но файл всегда пустой Вот мой код:
[assembly: Xamarin.Forms.Dependency(typeof(AndroidServiceHelper))]
namespace App6.Droid
{
internal class AndroidServiceHelper : IAndroidService
{
private static Context context = global::Android.App.Application.Context;
public void StartService()
{
var intent = new Intent(context, typeof(DataSource));
if(Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
{
context.StartForegroundService(intent);
}
else
{
context.StartService(intent);
}
}
public void StopService()
{
var intent = new Intent(context, typeof(DataSource));
context.StopService(intent);
}
}
}
namespace App6
{
public interface IAndroidService
{
void StartService();
void StopService();
}
}
namespace App6.Droid
{
internal class NotificationHelper : INotification
{
public static string foregroundChannelId = "9001";
private static Context context = global::Android.App.Application.Context;
public Notification ReturnNotif()
{
var intent = new Intent(context, typeof(MainActivity));
intent.AddFlags(ActivityFlags.SingleTop);
intent.PutExtra("Title", "Message");
var pendingIntent = PendingIntent.GetActivity(context, 0, intent, PendingIntentFlags.UpdateCurrent);
var notifBuilder = new NotificationCompat.Builder(context, foregroundChannelId)
.SetContentTitle("Your Title")
.SetContentText("Main Text Body")
.SetSmallIcon(Resource.Drawable.notify_panel_notification_icon_bg)
.SetOngoing(true)
.SetContentIntent(pendingIntent);
// Building channel if API verion is 26 or above
if (global::Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
NotificationChannel notificationChannel = new NotificationChannel(foregroundChannelId, "Title", NotificationImportance.High);
notificationChannel.Importance = NotificationImportance.High;
notificationChannel.EnableLights(true);
notificationChannel.EnableVibration(true);
notificationChannel.SetShowBadge(true);
notificationChannel.SetVibrationPattern(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 });
var notifManager = context.GetSystemService(Context.NotificationService) as NotificationManager;
if (notifManager != null)
{
notifBuilder.SetChannelId(foregroundChannelId);
notifManager.CreateNotificationChannel(notificationChannel);
}
}
return notifBuilder.Build();
}
}
}
namespace App6
{
public interface INotification
{
Notification ReturnNotif();
}
}
namespace App6
{
public class DataSource : Service
{
private string path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData), "s.txt");
public override IBinder OnBind(Intent intent)
{
return null;
}
public const int ServiceRunningNotifID = 9000;
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
Notification notif = DependencyService.Get<INotification>().ReturnNotif();
StartForeground(ServiceRunningNotifID, notif);
Proccesing();
return StartCommandResult.Sticky;
}
public override void OnDestroy()
{
base.OnDestroy();
}
public override bool StopService(Intent name)
{
return base.StopService(name);
}
public void Proccesing()
{
using(StreamWriter sw = File.AppendText(path))
{
sw.WriteLine(DateTime.Now.ToString());
}
}
}
}
namespace App6
{
public partial class MainPage : ContentPage
{
private string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "s.txt");
public MainPage()
{
InitializeComponent();
DependencyService.Get<IAndroidService>().StartService();
Timer timer = new Timer((o) =>
{
Device.BeginInvokeOnMainThread(() => label1.Text = File.ReadAllText(path));
}, null, 2000, 2000);
}
}
}