Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Wednesday, December 7, 2016 6:04 AM
Im trying to send data to the server every after 30 sec. it works perfectly if the app is running. but when i closed the app on the task manager the services stops running. anyone encounter this situation before and have solved it? Thanks.
All replies (9)
Thursday, December 8, 2016 2:00 AM âś…Answered
Thanks guys for your reply. heres my code on MainActivity.cs
using Android.App; using Android.Widget; using Android.OS; using Android.Content; using ReleaseModeApp_v3.Receiver;
namespace ReleaseModeAppv3 { [Activity(Label = "ReleaseModeAppv3", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : Activity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle);
var intent = new Intent(ApplicationContext, typeof(PostService));
var source = PendingIntent.GetBroadcast(ApplicationContext, 0, intent, 0);
}
}
}
and on heres my PostService code
using System; using System.Collections.Generic; using System.Linq; using System.Text;
using Android.App; 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;
namespace ReleaseModeApp_v3.Services { [Service] public class PostService : Service { CancellationTokenSource _cts; public override IBinder OnBind(Intent intent) { return null; }
public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId)
{
var t = new Java.Lang.Thread(() => {
_cts = new CancellationTokenSource();
Task.Run(() =>
{
try
{
var counter = new BackgroundTask();
counter.ExecutePost(_cts.Token).Wait();
}
catch (Android.Accounts.OperationCanceledException)
{
}
finally
{
if (_cts.IsCancellationRequested)
{
}
}
}, _cts.Token);
}
);
t.Start();
return StartCommandResult.Sticky;
}
}
}
and my BackgroundTask.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text;
using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using System.Threading.Tasks; using static Android.Bluetooth.BluetoothClass; using System.Threading; using ReleaseModeApp_v3.Models; using System.Net.Http; using Newtonsoft.Json;
namespace ReleaseModeApp_v3 { public class BackgroundTask {
public async Task ExecutePost(CancellationToken token)
{
await Task.Run(async () => {
while (1 < 2)
{
await Task.Delay(30000);
PostData();
}
}, token);
}
public async void PostData()
{
var deviceInformation = new DeviceInformation();
deviceInformation.BatteryStatus = 1;
deviceInformation.LocationLatitude = "123";
deviceInformation.LocationLatitude = "456";
deviceInformation.DeviceModel = "Samsing";
var client = new HttpClient();
client.BaseAddress = new Uri("urlhere");
var deviceInformationJson = JsonConvert.SerializeObject(deviceInformation);
var content = new StringContent(deviceInformationJson, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync("/index.php/send-email", content);
var result = await response.Content.ReadAsStringAsync();
}
}
}
Is this the right way to do it?
Wednesday, December 7, 2016 7:50 AM
Hy, you have to create your own SERVICE. Here are some guides how you can simply create you own first Service: https://developer.xamarin.com/guides/android/application*fundamentals/services/ https://developer.xamarin.com/guides/android/application*fundamentals/backgrounding/part*3*android*backgrounding*walkthrough/
You need to know if you mark an Activity with "SERVICE" like in this tutorials, their code will run in background even if you close your App. You only have to set then a Timer in your Background Service that fire a code every 30 Seconds. But remember your Background Code always has to be in a "Task". This also is showed and explained in the tutorials.
Good luck!
Wednesday, December 7, 2016 7:52 AM
You can add your service to the AlarmManager. Add it like this:
AlarmManager alarm = (AlarmManager)context.GetSystemService(Context.AlarmService);
PendingIntent pendingServiceIntent = PendingIntent.GetService(context, requestcode, new Intent(intent), PendingIntentFlags.UpdateCurrent);
alarm.SetRepeating(AlarmType.ElapsedRealtimeWakeup, 0, 30 * 1000, pendingServiceIntent);
For the AlarmType look at the documentation to see what fits you best.
Thursday, December 8, 2016 9:06 AM
hi guys i already figured it out. its on my android version ... the background service doesn't work on my marshmallow but its complete working on my lollipop ..
Thursday, January 18, 2018 10:59 AM
Hi all, I have tried android services but not help.when an app is close services also close. so suggest your idea.I have posted code and question in below-mentioned URL
Tuesday, September 18, 2018 2:22 AM
I tried on what the answer says. But still doens't run when the app is closed.
Tuesday, April 9, 2019 11:15 AM
@Bertwin I think this link will help you https://robgibbens.com/backgrounding-with-xamarin-forms/
Tuesday, April 30, 2019 8:11 AM
@Bertwin said: Thanks guys for your reply. heres my code on MainActivity.cs
using Android.App; using Android.Widget; using Android.OS; using Android.Content; using ReleaseModeApp_v3.Receiver;
namespace ReleaseModeAppv3 { [Activity(Label = "ReleaseModeAppv3", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : Activity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle);
var intent = new Intent(ApplicationContext, typeof(PostService)); var source = PendingIntent.GetBroadcast(ApplicationContext, 0, intent, 0); } }
}
and on heres my PostService code
using System; using System.Collections.Generic; using System.Linq; using System.Text;
using Android.App; 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;
namespace ReleaseModeApp_v3.Services { [Service] public class PostService : Service { CancellationTokenSource _cts; public override IBinder OnBind(Intent intent) { return null; }
public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId) { var t = new Java.Lang.Thread(() => { _cts = new CancellationTokenSource(); Task.Run(() => { try { var counter = new BackgroundTask(); counter.ExecutePost(_cts.Token).Wait(); } catch (Android.Accounts.OperationCanceledException) { } finally { if (_cts.IsCancellationRequested) { } } }, _cts.Token); } ); t.Start(); return StartCommandResult.Sticky; } }
}
and my BackgroundTask.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text;
using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using System.Threading.Tasks; using static Android.Bluetooth.BluetoothClass; using System.Threading; using ReleaseModeApp_v3.Models; using System.Net.Http; using Newtonsoft.Json;
namespace ReleaseModeApp_v3 { public class BackgroundTask {
public async Task ExecutePost(CancellationToken token) { await Task.Run(async () => { while (1 < 2) { await Task.Delay(30000); PostData(); } }, token); } public async void PostData() { var deviceInformation = new DeviceInformation(); deviceInformation.BatteryStatus = 1; deviceInformation.LocationLatitude = "123"; deviceInformation.LocationLatitude = "456"; deviceInformation.DeviceModel = "Samsing"; var client = new HttpClient(); client.BaseAddress = new Uri("urlhere"); var deviceInformationJson = JsonConvert.SerializeObject(deviceInformation); var content = new StringContent(deviceInformationJson, Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync("/index.php/send-email", content); var result = await response.Content.ReadAsStringAsync(); } }
}
Is this the right way to do it?
Is it work when close app, clear from recent list app?
Thursday, November 7, 2019 2:30 PM
Hello, I would like to know if someone has a code that works when the app closes and the service continues to work.