Background service not work Xamarin.Android - c#

I have problem. My service worked, but when i close application service stoped.
How i can leave my service is running?
service
[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();
}

When we start application from VS and stop an application. VS automatically close all services. Need build the app to the device and than start application from device.

Sorry for the late answer but I think it can help others. I would like to make something clear for you that you are writing this service as a background service. Background service can not run for long. There are some limitation of background services in Android after Android 8.0 onwards. Android automatically kills background service of an app after some time.
See this https://developer.android.com/about/versions/oreo/background
If you want to run a service for a long time then make the service Foreground Service. Please follow https://learn.microsoft.com/en-us/xamarin/android/app-fundamentals/services/foreground-services for detailed knowledge of foreground service in Xamarin Forms.

Related

java.lang.IllegalArgumentException: No such service ComponentInfo{/com.SampleApp.AttendanceApp.ServiceClass}

I am using Xamarin Android to build an app which should allow the app to keep sending a driver's location every 15 minutes so that I can keep track of his movement. I used JobScheduler to get this done. My project is very simple now and only contains the following 3 files:
MainActivity.cs
AttendancePage.cs (Content page, interact with UI button to start the service)
ServiceClass.cs
Methods in Main Activity.cs
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
scheduler = (JobScheduler)GetSystemService(JobSchedulerService);
LoadApplication(new App()); //This line will then jump to AttendancePage.cs
}
public void ScheduleJob()
{
ComponentName componentName = new ComponentName(this, Java.Lang.Class.FromType(typeof(ServiceClass)));
JobInfo info = new JobInfo.Builder(123, componentName)
.SetPersisted(true)
.SetPeriodic(60000)
.Build();
int resultCode = scheduler.Schedule(info); //The error show when hit this line.
if (resultCode == JobScheduler.ResultSuccess)
{
Log.Info("Message", "Job Schedule!");
}
else
{
Log.Info("Message", "Job shceduling failed");
}
}
public void CancelJob()
{
scheduler.Cancel(123);
}
AttendancePage.cs
public partial class AttendancePage : ContentPage
{
MainActivity main = new MainActivity();
public AttendancePage()
{
InitializeComponent();
Title = "Attendance App";
}
//Button OnClickEvent
async void ScheduleJob(object s, EventArgs e)
{
main.ScheduleJob();
}
//Button OnClickEvent
async void CancelJob(object s, EventArgs e)
{
main.CancelJob();
}
}
ServiceClass.cs
[Service(Name = "com.SampleApp.AttendanceApp.ServiceClass", Permission = "android.permission.BIND_JOB_SERVICE")]
public class ServiceClass : JobService
{
public ServiceClass()
{
}
public override bool OnStartJob(JobParameters jobParamsOnStart)
{
doBackgroundWork(jobParamsOnStart);
return true;
}
private void doBackgroundWork(JobParameters jobParam)
{
//My code to send driver's location
TestingPage.GetGPS();
JobFinished(jobParam, false);
}
public override bool OnStopJob(JobParameters jobParamsOnStop)
{
return false;
}
}
I have added the service tag inside AndroidManifest.xml as well.
<service android:name=".ServiceClass"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="true" />
I have no idea why the error is still there. The error is from the line scheduler.Schedule(JobInfo). Anyone has another possible solution? I am frustrated on solving this. Will the reason be I can't debug on the service but only can straight away run in release mode? Please help.
Froms shared code it works in Xamarin.Android project , however here is a Xamarin.Forms project . It can not work.
In AttendancePage.cs , you create a new MainActivity to invoke the native method ScheduleJob and CancelJob . This will not find the JobScheduler in native ,then it will return null .
No such service ComponentInfo{/com.SampleApp.AttendanceApp.ServiceClass}
If you want to invoke native method , you can have a try with DependencyService in Xamarin Forms .
At least need to create a Interface in Forms to invoke :
public interface IJobSchedulerService
{
//Start JobSchedule
void StartJobSchedule();
//Cancel JobSchedule
void CancelJobSchedule();
}
Then can invoke in Xamarin Forms as follow :
async void ScheduleJob(object s, EventArgs e)
{
DependencyService.Get<IJobSchedulerService>().StartJobSchedule();
}
//Button OnClickEvent
async void CancelJob(object s, EventArgs e)
{
DependencyService.Get<IJobSchedulerService>().CancelJobSchedule();
}
Now you need to implement the IJobSchedulerService in native android .Create the JobSchedulerDependcenyService:
public class JobSchedulerDependcenyService : IJobSchedulerService
{
JobScheduler jobScheduler;
public JobSchedulerDependcenyService()
{
jobScheduler = (JobScheduler)MainActivity.Instance.GetSystemService(Android.Content.Context.JobSchedulerService);
}
public void StartJobSchedule()
{
ComponentName componentName = new ComponentName(MainActivity.Instance, Java.Lang.Class.FromType(typeof(DownloadJob)));
JobInfo jobInfo = new JobInfo.Builder(1, componentName)
.SetOverrideDeadline(0)
.Build();
//var jobScheduler = (JobScheduler)GetSystemService(JobSchedulerService);
var scheduleResult = jobScheduler.Schedule(jobInfo);
if (JobScheduler.ResultSuccess == scheduleResult)
{
var snackBar = Snackbar.Make(MainActivity.Instance.FindViewById(Android.Resource.Id.Content), "jobscheduled_success", Snackbar.LengthShort);
snackBar.Show();
}
else
{
var snackBar = Snackbar.Make(MainActivity.Instance.FindViewById(Android.Resource.Id.Content), "jobscheduled_failure", Snackbar.LengthShort);
snackBar.Show();
}
}
public void CancelJobSchedule()
{
jobScheduler.CancelAll();
}
}
Here you will find the MainActivity.Instance inside it , that's a static instance defined by self in MainActivity.
public static MainActivity Instance { set; get; }
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Instance = this;
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}

Wait is being ignored by code and passing straight through on Xamarin.Android

I need to open my popup screen when my method is called, but it is being ignored by my await and does not show the popup.
This is for an android device and I am using rg.plugins.popup to display my popup page and I'm using VS17 as the IDE.
So far I've also tried calling my method synchronously but that doesn't seem to work either.
public async void PegaValor(bool retry)
{
await PopupNavigation.PushAsync(new Paginas.PopupTentarNovamente());
Paginas.PopupTentarNovamente tentarNovamente = new Paginas.PopupTentarNovamente();
if (tentarNovamente.resultado)
{
retry = false;
}
else
{
retry = true;
}
}
I have a suspicion that the pop up needs to be ran on the main UI Dispatcher, I'd suggest trying the following:
public async void PegaValor(bool retry)
{
Activity.RunOnUiThread(async () => {
await PopupNavigation.PushAsync(new Paginas.PopupTentarNovamente());
});
Paginas.PopupTentarNovamente tentarNovamente = new Paginas.PopupTentarNovamente();
if (tentarNovamente.resultado)
{
retry = false;
}
else
{
retry = true;
}
}
EDIT:
Based on your comments and taking a quick look at your github link here are a couple of ways you can do what I suggested, although I still have no clue how your instantiating the class from the git repo.
So for a quick example, this way assumes your using that class inside of an activity, so you could try the following
// Create an instance of metodosEmpenho in your activity and pass through the Activity as a parameter to the constructor.
public class MyActivity : Activity
{
private MetodosEmpenho metodosEmpenho;
protected override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
metodosEmpenho = new MetodosEmpenho(Context as Activity);
metodosEmpenho.VerOperador("");
}
}
// Create a consturctor in the MetodosEmpenho class that will take the Activity paramter and store it for later use.
public class MetodosEmpenho
{
private readonly Activity _activity
public MetodosEmpenho(Activity currActivity)
{
_activity = currActivity;
}
public async void PegaValor(bool retry)
{
_activity.RunOnUiThread(async () => {
await PopupNavigation.PushAsync(new Paginas.PopupTentarNovamente());
});
Paginas.PopupTentarNovamente tentarNovamente = new Paginas.PopupTentarNovamente();
if (tentarNovamente.resultado)
{
retry = false;
}
else
{
retry = true;
}
}
}

xamarin Android Service Stops When App Is Closed

I am totally new in Xamarin. I am trying to run the service when the application gets closed. But as I closed the app from the recent item service getting stop and getting message projectname.android has stopped. I want service should run as in whatsapp after closed the app then also service run. Anyone know the answer please help.
Here is my service class Code. This code sent the notification each 5 sec. using local notification plugin library. but this code running fine in android 5 version
class AndroidService : Service
{
private Timer _check_Timer_Data;
public override IBinder OnBind(Intent intent)
{
return null;
}
[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
base.OnStartCommand(intent, flags, startId);
var t = new Thread(() =>
{
_check_Timer_Data = new Timer((o) =>
{
Random rdno = new Random();
int id = rdno.Next(1000);
string dt = DateTime.Now.ToString("h:mm:ss tt");
CrossLocalNotifications.Current.Show("G7CR", "G7CR Notification-" + dt, id);
}, null, 0, 5000);
}
);
t.Start();
return StartCommandResult.Sticky;
}
public override void OnDestroy()
{
base.OnDestroy();
_check_Timer_Data.Dispose();
}
public override void OnCreate()
{
base.OnCreate();
}
}

Xamarin forms background service is killed when app is killed

I am making use of Prism in my xamarin forms project.I am also making use of background services to push long running tasks in the background.The problem is when the app is killed the service is also killed.And by "killed" I mean press home-button -> see all running apps -> swipe my app aside -> app killed .I want to keep the service alive even if the app is killed.I have read many posts which say that it can be done.However I was not able to get it working.
This is what I have tried :-
This is Android MainActivity.cs
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
try
{
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App(new AndroidInitializer()));
WireUpLongRunningTask();
}
catch(Exception)
{
}
}
public void WireUpLongRunningTask()
{
MessagingCenter.Subscribe<StartSyncBackgroundingTask>(this, "StartSyncBackgroundingTask", message => {
var intent = new Intent(this, typeof(AndroidSyncBackgroundService));
StartService(intent);
});
}
This is AndroidSyncBackgroundService class :-
[Service]
public class AndroidSyncBackgroundService : Service
{
CancellationTokenSource _cts;
private ISyncBackgroundService _isyncBackgroundService;
private App _app => (App)Xamarin.Forms.Application.Current;
public override IBinder OnBind(Intent intent)
{
return null;
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
_cts = new CancellationTokenSource();
Task.Run(() => {
try {
//INVOKE THE SHARED CODE
_isyncBackgroundService = _app.Container.Resolve<ISyncBackgroundService>();
_isyncBackgroundService.RunBackgroundingCode(_cts.Token).Wait();
}
catch (System.OperationCanceledException) {
}
finally {
if (_cts.IsCancellationRequested) {
var message = new CancelledTask();
Device.BeginInvokeOnMainThread(
() => MessagingCenter.Send(message, "CancelledTask")
);
}
}
}, _cts.Token);
return StartCommandResult.Sticky;
}
public override void OnDestroy()
{
if (_cts != null) {
_cts.Token.ThrowIfCancellationRequested();
_cts.Cancel();
}
StartService(new Intent("com.xamarin.AndroidSyncBackgroundService"));
base.OnDestroy();
}
public override void OnTaskRemoved(Intent rootIntent)
{
Intent restartServiceIntent = new Intent(Xamarin.Forms.Forms.Context, typeof(AndroidSyncBackgroundService));
PendingIntent restartServicePendingIntent = PendingIntent.GetService(Xamarin.Forms.Forms.Context, 1, restartServiceIntent,PendingIntentFlags.OneShot);
AlarmManager alarmService = (AlarmManager)Xamarin.Forms.Forms.Context.GetSystemService(Context.AlarmService);
alarmService.Set(
AlarmType.ElapsedRealtime,
1000,
restartServicePendingIntent);
base.OnTaskRemoved(rootIntent);
}
}
This is SyncBackgroundService class :-
public class SyncBackgroundService: ISyncBackgroundService
{
private ISqliteCallsService _iSqliteCallsService;
private IFeedBackSqliteService _feedBackSqliteService;
private ISettingApiService _isettingApiService;
private ISettingSqliteService _isettingSqliteService;
private IWebApiService _iwebApiService;
private App _app => (App)Xamarin.Forms.Application.Current;
public async Task RunBackgroundingCode(CancellationToken token)
{
_iSqliteCallsService= _app.Container.Resolve<ISqliteCallsService>();
await Task.Run(async () => {
token.ThrowIfCancellationRequested();
App.bRunningBackgroundTask = true;
await Task.Run(async () =>
{
await Task.Delay(1);
_iSqliteCallsService.ftnSaveOnlineModeXMLFormat("Offline", 0);
_iSqliteCallsService.SyncEmployeeTableData();
_iSqliteCallsService.SaveOfflineAppCommentData();
_iSqliteCallsService.SaveOfflineAdditionToFlowData();
await Task.Delay(500);
//MessagingCenter.Send<SyncBackgroundService>(this, "StopSyncBackgroundingTask");
});
}, token);
}
}
}
As can be seen in the code snippet I have made use of StartCommandResult.Sticky and still the service gets killed and does not restart.
Also i'm making use of Alarm Manager in OnTaskRemoved method,which gets fired when the app is killed according to its documentation.But in my case the service does not restart atall.Can somebody point out what is the mistake in my code? Or provide a working solution so that I can implement it in my app.
Thanks in advance!
Try this after you call StartService
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat)
{
PendingIntent pintent = PendingIntent.GetService(AppContext, 0, new Intent(AppContext, typeof(AndroidSyncBackgroundService )), 0);
AlarmManager alarm = (AlarmManager)AppContext.GetSystemService(Context.AlarmService);
alarm.Cancel(pintent);
}
The reason this might work is because Android schedules your service to be killed after your app is killed. Doing this removes that scheduled task.

Xamarin Android Background Service crashes when the Application get closed

Hello, I want to build an app, in which you can start a service, which runs intependenly and creates a notification, and this service should constantly proof, if the DateTime.Now.Date is bigger than a spezific Date.
When I execute the code below, the notification gets displayed, but when I am closing the app, a few secondes later I get two times an information that the app crashed and I dont know why.
I cant even debug the code because this anly happens when the application is closed....
I hope you can help me thanks!
Here is my code:
namespace App
{
[Activity(Label = "App", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
int count = 1;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
Button button = FindViewById<Button>(Resource.Id.MyButton);
button.Click += delegate {
button.Text = string.Format("{0} clicks!", count++);
StartService(new Intent(this, typeof(backgroudservice)));
};
}
}
public class backgroudservice : Service
{
public override IBinder OnBind(Intent intent)
{
return null;
}
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
newnotification("Title", "Text: ", 0);
new Task(() => {
DoWork();
Thread.Sleep(1000);
}).Start();
return StartCommandResult.Sticky;
}
public void DoWork()
{
if (DateTime.Now.Date > Convert.ToDateTime("2016-03-29").Date)
{
cancelnotification(0);
StopSelf();
}
}
public override void OnDestroy()
{
base.OnDestroy();
cancelnotification(0);
}
private void newnotification(string titel, string text, int id)
{
Notification.Builder builder = new Notification.Builder(this)
.SetContentTitle(titel)
.SetContentText(text)
.SetSmallIcon(Resource.Drawable.droidlogo_small)
.SetAutoCancel(false)
.SetVisibility(NotificationVisibility.Public)
.SetContentIntent(PendingIntent.GetActivity(this, 0, new Intent(this, typeof(MainActivity)), PendingIntentFlags.OneShot));
// Build the notification:
Notification notification = builder.Build();
notification.Flags = NotificationFlags.NoClear;
//notification.ContentIntent = new Intent(this,typeof(login));
// Get the notification manager:
NotificationManager notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
// Publish the notification:
notificationManager.Notify(id, notification);
}
private void cancelnotification(int id)
{
NotificationManager notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
notificationManager.Cancel(id);
}
}
}
I solved it, I forgot the [Service] above my class, now it works!
[Service]
public class backgroudservice : Service
{
...
}
You might try moving the call to cancelnotification in your service's OnDestroy to before the call to the base method, i.e.:
public override void OnDestroy()
{
cancelnotification(0);
base.OnDestroy();
}

Categories