How can I call method defined in my PCL project to Android project ?
I have a method DoWork() defined in my PCL and I want this method to continuously be run in a service defined in my android project as follows:
public class BroadcastService : Service
{
IBinder mBinder;
[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
Toast.MakeText(this, "BroadcastService is running ", ToastLength.Long).Show();
Task.Run(() =>
{
var counter = new Counter();
counter.DoWork().Wait();
});
base.OnStartCommand(intent, flags, startId);
return StartCommandResult.Sticky;
}
The toast is appearing.
However, the DoWork() is not running. Can someone enlighten what is wrong please?
The full method signature for DoWork() :
private async void DoWork()
{
StartDetect();
Device.StartTimer(TimeSpan.FromSeconds(20), () =>
{
_foundTags = _truck.GetAvailableTrucks();
DoWork();
});
}
I think you can use a MessagingCenter. You can try something like this
public class BroadcastService : Service
{
IBinder mBinder;
[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
Toast.MakeText(this, "BroadcastService is running ", ToastLength.Long).Show();
Xamarin.Forms.MessagingCenter.Send<App>((App)Xamarin.Forms.Application.Current, "dowork");
base.OnStartCommand(intent, flags, startId);
return StartCommandResult.Sticky;
}
and in your PCL project
protected override void OnStart()
{
MessagingCenter.Subscribe<App>(this, "dowork", (sender) =>
{
// Do something here
});
// Handle when your app starts
}
Related
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();
}
}
I'm developing an Android application with Xamarin Forms that is composed of an interface and also a background service.
I need that the service works also when the interface application is closed.
If I add "IsolatedProcess = true" into the service the graphical interface still works but the service crashes.
I read a lot of posts with possible solutions but they don't work. (I tried to compile in release mode and also to remove "Use Shared Runtime" flag).
I'm compiling with Android 8.1 (Oreo) as Target Framework.
The target environment is Android 4.2.
I start the service into OnCreate method of the MainActivity class:
Intent testIntent = new Intent(this.BaseContext, typeof(TestService));
StartService(testIntent);
The service class:
[Service(IsolatedProcess = true, Exported = true, Label = "TestService")]
public class TestService : Service
{
public override IBinder OnBind(Intent intent)
{
return null;
}
public override void OnCreate()
{
base.OnCreate();
}
[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
Device.StartTimer(new TimeSpan(0, 0, 40), () =>
{
//Code executed every 40 seconds
});
base.OnStartCommand(intent, flags, startId);
return StartCommandResult.Sticky;
}
public override bool StopService(Intent name)
{
return base.StopService(name);
}
}
If I remove "IsolatedProcess = true" the service works but it will be stopped when I will close the application interface process.
I solved the issue by changing the value of the attribute IsolatedProcess to true, removing the Device.StartTimer instruction and by introducing a BroadcastReceiver.
MainActivity class:
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
public static Intent testServiceIntent;
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
testServiceIntent = new Intent(this.BaseContext, typeof(TestService));
LoadApplication(new App());
}
}
The service class:
[Service(IsolatedProcess = false, Exported = true, Label = "TestService")]
public class TestService : Service
{
System.Threading.Timer _timer;
public override IBinder OnBind(Intent intent)
{
return null;
}
public override void OnCreate()
{
base.OnCreate();
}
[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
businessLogicMethod();
base.OnStartCommand(intent, flags, startId);
return StartCommandResult.Sticky;
}
public void businessLogicMethod()
{
//My business logic in a System.Threading.Timer
}
}
The Broadcast Receiver class:
[BroadcastReceiver]
[IntentFilter(new[] { Intent.ActionBootCompleted })]
public class TestApplicationBroadcastReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
Log.Info("TestApp", "******* Loading Application *******");
try
{
if (intent.Action.Equals(Intent.ActionBootCompleted))
{
Intent service = new Intent(context, typeof(TestService));
service.AddFlags(ActivityFlags.NewTask);
context.StartService(service);
}
}
catch (Exception ex)
{
Log.Error("TestApp", "******* Error message *******: " + ex.Message);
}
}
}
I hope that can be useful for someone.
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.
I'd like to create notificiation in my app, which is going to be showed in 10 seconds. It works well, when application is running, but when I close the application, notification is not showed. Here is my code:
My notification service:
[Service]
class NotifyEvent : IntentService
{
protected override void OnHandleIntent(Intent intent)
{
PendingIntent pIntent = PendingIntent.GetActivity(this, 0, intent, 0);
Notification.Builder builder = new Notification.Builder(this);
builder.SetContentTitle(Resources.GetString(Resource.String.NotifikaceNadpis));
builder.SetContentText(Resources.GetString(Resource.String.NotifikaceText));
builder.SetSmallIcon(Resource.Drawable.Icon);
builder.SetPriority(1);
builder.SetDefaults(NotificationDefaults.Sound | NotificationDefaults.Vibrate);
builder.SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis());
Notification notifikace = builder.Build();
NotificationManager notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
const int notificationId = 0;
notificationManager.Notify(notificationId, notifikace);
}
}
Class, which starts notification:
public class Notificator
{
public void ShowNotification(Context context)
{
Intent intent = new Intent(context, typeof(NotifyEvent));
var pendingServiceIntent = PendingIntent.GetService(context, 0, intent, PendingIntentFlags.UpdateCurrent);
AlarmManager alarm = (AlarmManager)context.GetSystemService(Context.AlarmService);
alarm.Set(AlarmType.ElapsedRealtimeWakeup, SystemClock.ElapsedRealtime() + 10000, pendingServiceIntent);
}
}
Method in activity:
Notificator not = new Notificator();
not.ShowNotification(this);
My Activity:
[Activity(Label = "Nastavení")]
public class SettingsActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your application here
SetContentView(Resource.Layout.Settings);
Button vynulovatButton = FindViewById<Button>(Resource.Id.buttonRestartDne);
vynulovatButton.Click += VynulovatDen;
}
...
protected void VynulovatDen(object sender, EventArgs e)
{
Notificator not = new Notificator();
not.ShowNotification(this);
}
}
Thanks for every help.
you can try this.
protected override void OnDestroy()
{
Notificator not = new Notificator();
not.ShowNotification(this);
base.OnDestroy();
}
You should keep your service alive when you destroy your application.
add return StartCommandResult.Sticky; in the OnStartCommand method.
start the service OnTaskRemoved function.
Create your service with the Service interface, the IntentService is for Time-consuming operation.
class NotifyEvent : Service
{
[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
new Task(() => {
PendingIntent pIntent = PendingIntent.GetActivity(this, 0, intent, 0);
Notification.Builder builder = new Notification.Builder(this);
builder.SetContentTitle("hello");
builder.SetContentText("hello");
builder.SetSmallIcon(Resource.Drawable.Icon);
builder.SetPriority(1);
builder.SetDefaults(NotificationDefaults.Sound | NotificationDefaults.Vibrate);
builder.SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis());
Notification notifikace = builder.Build();
NotificationManager notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
const int notificationId = 0;
notificationManager.Notify(notificationId, notifikace);
}).Start();
return StartCommandResult.Sticky;
}
public override IBinder OnBind(Intent intent)
{
return null;
}
public override void OnTaskRemoved(Intent rootIntent)
{
Intent restartService = new Intent(ApplicationContext, typeof(NotifyEvent));
restartService.SetPackage(PackageName);
var pendingServiceIntent = PendingIntent.GetService(ApplicationContext, 0, restartService, PendingIntentFlags.UpdateCurrent);
AlarmManager alarm = (AlarmManager)ApplicationContext.GetSystemService(Context.AlarmService);
alarm.Set(AlarmType.ElapsedRealtime, SystemClock.ElapsedRealtime() + 1000, pendingServiceIntent);
System.Console.WriteLine("service OnTaskRemoved");
base.OnTaskRemoved(rootIntent);
}
}
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();
}