Should I use BroadcastReciver or Service with alarm manager?
Should I call my service via broadcast receiver or directly call it using alarm manger. Currently I'm using service directly but some times the alarm is not triggered.
PendingIntent pendingIntent = PendingIntent.getService(getContext().getApplicationContext(), 1, myIntent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmMgr = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pendingIntent);
add a comment |
Should I call my service via broadcast receiver or directly call it using alarm manger. Currently I'm using service directly but some times the alarm is not triggered.
PendingIntent pendingIntent = PendingIntent.getService(getContext().getApplicationContext(), 1, myIntent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmMgr = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pendingIntent);
1
honestly i dont see any difference if yourIntentpoints to aServiceorBroadcastReceiver- but you could check WorkManager sources and see how they do that
– pskink
Jan 1 at 10:00
this oneandroidx/work/impl/background/systemalarm/SystemAlarmService.javain particular - it is executed fromandroidx/work/impl/background/systemalarm/Alarms.java
– pskink
Jan 1 at 10:19
add a comment |
Should I call my service via broadcast receiver or directly call it using alarm manger. Currently I'm using service directly but some times the alarm is not triggered.
PendingIntent pendingIntent = PendingIntent.getService(getContext().getApplicationContext(), 1, myIntent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmMgr = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pendingIntent);
Should I call my service via broadcast receiver or directly call it using alarm manger. Currently I'm using service directly but some times the alarm is not triggered.
PendingIntent pendingIntent = PendingIntent.getService(getContext().getApplicationContext(), 1, myIntent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmMgr = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pendingIntent);
edited Jan 1 at 8:50
asif ali
1114
1114
asked Jan 1 at 8:38
Ross LamenRoss Lamen
12
12
1
honestly i dont see any difference if yourIntentpoints to aServiceorBroadcastReceiver- but you could check WorkManager sources and see how they do that
– pskink
Jan 1 at 10:00
this oneandroidx/work/impl/background/systemalarm/SystemAlarmService.javain particular - it is executed fromandroidx/work/impl/background/systemalarm/Alarms.java
– pskink
Jan 1 at 10:19
add a comment |
1
honestly i dont see any difference if yourIntentpoints to aServiceorBroadcastReceiver- but you could check WorkManager sources and see how they do that
– pskink
Jan 1 at 10:00
this oneandroidx/work/impl/background/systemalarm/SystemAlarmService.javain particular - it is executed fromandroidx/work/impl/background/systemalarm/Alarms.java
– pskink
Jan 1 at 10:19
1
1
honestly i dont see any difference if your
Intent points to a Service or BroadcastReceiver - but you could check WorkManager sources and see how they do that– pskink
Jan 1 at 10:00
honestly i dont see any difference if your
Intent points to a Service or BroadcastReceiver - but you could check WorkManager sources and see how they do that– pskink
Jan 1 at 10:00
this one
androidx/work/impl/background/systemalarm/SystemAlarmService.java in particular - it is executed from androidx/work/impl/background/systemalarm/Alarms.java– pskink
Jan 1 at 10:19
this one
androidx/work/impl/background/systemalarm/SystemAlarmService.java in particular - it is executed from androidx/work/impl/background/systemalarm/Alarms.java– pskink
Jan 1 at 10:19
add a comment |
3 Answers
3
active
oldest
votes
BroadcastReceiver is not for any type of long-running operations (whether synchronous or asynchronously waiting for some callback). It is simply used for receiving some event (broadcast) then handing off any longer-running action to the appropriate component (i.e. Activity or Service).
IntentService is for a long-running, synchronous operation that is handled on another thread. A (foreground) service allows you to more or less act as an invisible Activity. You can await asynchronous callbacks (i.e. the user dismissing the alarm).
You can use this library i have made.
service in background and foreground with it you run service and than receive the call with broadcast
with simple code you start call or start your service like this
RunService service = new RunService(this);
service.call(5);
and do your action inside this method
BroadcastReceiver alarm_receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// your logic here
Log.i("alarm_received", "success");
}
};
dont forget to register the service and remove the service on destroy same as you see in the documentation.
But this dosen't answer my question.
– Ross Lamen
Jan 1 at 9:28
updated my answer
– Hossam Hassan
Jan 1 at 9:33
What I'm asking is should I start a service from a BroadcastReciver or directly call it from an alarm manger. Generally most people call the service from BroadcastReciver. I want to know what is the right practice.
– Ross Lamen
Jan 1 at 9:49
theres no reason at all to call it from broadcast, you should call it directly
– Hossam Hassan
Jan 1 at 9:51
add a comment |
I suggest using Broadcast receiver and when onReceive you can fire service or do anything, also it's useful especially when you need to receive android.intent.action.BOOT_COMPLETED to reschedule your pending alarms because when the device restarted the OS will delete any pending alarms, for more info check this link
add a comment |
namespace Diabetes.Droid
{
[Application]
public class MainApplication : Application
{
ISetAlarm alarmService;
public static Context AppContext;
public MainApplication()
{
}
public MainApplication(IntPtr handle, JniHandleOwnership transer) : base(handle, transer)
{
}
public override void OnCreate()
{
base.OnCreate();
AppContext = this.ApplicationContext;
alarmService = new SetAlarmImplementation();
alarmService.SetAlarm(13,58,"hello","great work ");
}
public void SetAlarm(int hour, int minute, string title, string message)
{
AppContext.StartService(new Intent(AppContext, typeof(AppStickyService)));
Intent myintent = new Intent(Android.App.Application.Context, typeof(AppStickyService));
myintent.PutExtra("message", message);
myintent.PutExtra("title", title);
//PendingIntent pendingintent = PendingIntent.GetBroadcast(Android.App.Application.Context, 0, myintent, PendingIntentFlags.UpdateCurrent);
PendingIntent pintent = PendingIntent.GetService(AppContext, 0, new Intent(AppContext, typeof(AppStickyService)), 0);
Java.Util.Date date = new Java.Util.Date();
Java.Util.Calendar cal = Java.Util.Calendar.Instance;
cal.TimeInMillis = Java.Lang.JavaSystem.CurrentTimeMillis();
cal.Set(Java.Util.CalendarField.HourOfDay, hour);
cal.Set(Java.Util.CalendarField.Minute, minute);
cal.Set(Java.Util.CalendarField.Second, 0);
AlarmManager alarmManager = Android.App.Application.Context.GetSystemService(Android.Content.Context.AlarmService) as AlarmManager;
alarmManager.Set(AlarmType.RtcWakeup, cal.TimeInMillis, pintent);
// alarmManager.Cancel(pintent);
}
public void StartService()
{
AppContext.StartService(new Intent(AppContext, typeof(AppStickyService)));
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat)
{
PendingIntent pintent = PendingIntent.GetService(AppContext, 0, new Intent(AppContext, typeof(AppStickyService)), 0);
//AlarmManager alarm = (AlarmManager)AppContext.GetSystemService(Context.AlarmService);
Toast.MakeText(this, "Service started", ToastLength.Long).Show();
//alarm.Cancel(pintent);
}
}
public static void StopService()
{
AppContext.StopService(new Intent(AppContext, typeof(AppStickyService)));
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat)
{
// Toast.MakeText(this,"Service started", ToastLength.Long).Show();
//PendingIntent pintent = PendingIntent.GetService(AppContext, 0, new Intent(AppContext, typeof(AppStickyService)), 0);
// AlarmManager alarm = (AlarmManager)AppContext.GetSystemService(Context.AlarmService);
//alarm.Cancel(pintent);
}
}
}
This is AlarmImplementation.class
public class SetAlarmImplementation : ISetAlarm
{
public SetAlarmImplementation(){}
public void SetAlarm(int hour, int minute, string title, string message)
{
Intent myintent = new Intent(Android.App.Application.Context, typeof(AlarmReceiver));
myintent.PutExtra("message", message);
myintent.PutExtra("title", title);
PendingIntent pendingintent = PendingIntent.GetBroadcast(Android.App.Application.Context, 0, myintent, PendingIntentFlags.UpdateCurrent);
Java.Util.Date date = new Java.Util.Date();
Java.Util.Calendar cal = Java.Util.Calendar.Instance;
cal.TimeInMillis = Java.Lang.JavaSystem.CurrentTimeMillis();
cal.Set(Java.Util.CalendarField.HourOfDay, hour);
cal.Set(Java.Util.CalendarField.Minute, minute);
cal.Set(Java.Util.CalendarField.Second, 0);
AlarmManager alarmManager = Android.App.Application.Context.GetSystemService(Android.Content.Context.AlarmService) as AlarmManager;
alarmManager.Set(AlarmType.RtcWakeup, cal.TimeInMillis, pendingintent);
}
}
This is BroadcastReceiver.class
[BroadcastReceiver]
[IntentFilter(new string { "android.intent.action.BOOT_COMPLETED" }, Priority = (int)IntentFilterPriority.LowPriority)]
public class AlarmReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
var message = intent.GetStringExtra("message");
var title = intent.GetStringExtra("title");
//Show toast here
//Toast.MakeText(context, "Hello it's me ", ToastLength.Short).Show();
var extras = intent.Extras;
if (extras != null && !extras.IsEmpty)
{
NotificationManager manager_ = context.GetSystemService(Context.NotificationService) as NotificationManager;
var notificationId = extras.GetInt("NotificationIdKey", -1);
if (notificationId != -1)
{
manager_.Cancel(notificationId);
}
}
//Create intent for action 1 (TAKE)
var actionIntent1 = new Intent();
actionIntent1.SetAction("ARCHIVE");
var pIntent1 = PendingIntent.GetBroadcast(context, 0, actionIntent1, PendingIntentFlags.CancelCurrent);
//Create intent for action 2 (REPLY)
var actionIntent2 = new Intent();
actionIntent2.SetAction("REPLY");
var pIntent2 = PendingIntent.GetBroadcast(context, 0, actionIntent2, PendingIntentFlags.CancelCurrent);
Intent resultIntent = context.PackageManager.GetLaunchIntentForPackage(context.PackageName);
var contentIntent = PendingIntent.GetActivity(context, 0, resultIntent, PendingIntentFlags.CancelCurrent);
var pending = PendingIntent.GetActivity(context, 0,
resultIntent,
PendingIntentFlags.CancelCurrent);
//seting an alarm
MedicationDatabase db = new MedicationDatabase();
var alarm_list = db.GetAlarmList();
//Debug.WriteLine(" Time -- : "+ m.ToString());
// Instantiate the Big Text style:
Notification.BigTextStyle textStyle = new Notification.BigTextStyle();
var builder =
new Notification.Builder(context)
.AddAction(Resource.Drawable.tick_notify, "ARCHIVE", pIntent1)
.AddAction(Resource.Drawable.cancel_notify, "REPLY", pIntent2)
.SetSmallIcon(Resource.Drawable.ic_launcher)
.SetContentTitle("Diabetics Reminder")
.SetDefaults(NotificationDefaults.Sound)
.SetStyle(new Notification
.BigTextStyle()
.SetSummaryText("")
.SetBigContentTitle(title)
.BigText(message)
).SetDefaults(NotificationDefaults.All);
builder.SetContentIntent(pending);
var notification = builder.Build();
var manager = NotificationManager.FromContext(context);
manager.Notify(10010, notification);
}
}
and this is the final service class
[Service]
public class AppStickyService : Service
{
public override void OnCreate()
{
base.OnCreate();
// Toast.MakeText(this, "Service started Habiibi", ToastLength.Long).Show();
//WireAlarm();
System.Diagnostics.Debug.WriteLine("Sticky Service - Created");
}
public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId)
{
SetAlarm(12,39,"Try","Start Service");
return StartCommandResult.Sticky;
}
public override Android.OS.IBinder OnBind(Android.Content.Intent intent)
{
System.Diagnostics.Debug.WriteLine("Sticky Service - Binded");
//WireAlarm();
return null;
}
public override void OnDestroy()
{
System.Diagnostics.Debug.WriteLine("Sticky Service - Destroyed");
base.OnDestroy();
WireAlarm();
}
can you elaborate more on the answer?
– Moshe Slavin
Jan 1 at 9:16
this code to be having a sticky service as in when the Application is Idle or sleeping it makes a notification.
– deepak sharma
Jan 1 at 9:26
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53994093%2fshould-i-use-broadcastreciver-or-service-with-alarm-manager%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
BroadcastReceiver is not for any type of long-running operations (whether synchronous or asynchronously waiting for some callback). It is simply used for receiving some event (broadcast) then handing off any longer-running action to the appropriate component (i.e. Activity or Service).
IntentService is for a long-running, synchronous operation that is handled on another thread. A (foreground) service allows you to more or less act as an invisible Activity. You can await asynchronous callbacks (i.e. the user dismissing the alarm).
You can use this library i have made.
service in background and foreground with it you run service and than receive the call with broadcast
with simple code you start call or start your service like this
RunService service = new RunService(this);
service.call(5);
and do your action inside this method
BroadcastReceiver alarm_receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// your logic here
Log.i("alarm_received", "success");
}
};
dont forget to register the service and remove the service on destroy same as you see in the documentation.
But this dosen't answer my question.
– Ross Lamen
Jan 1 at 9:28
updated my answer
– Hossam Hassan
Jan 1 at 9:33
What I'm asking is should I start a service from a BroadcastReciver or directly call it from an alarm manger. Generally most people call the service from BroadcastReciver. I want to know what is the right practice.
– Ross Lamen
Jan 1 at 9:49
theres no reason at all to call it from broadcast, you should call it directly
– Hossam Hassan
Jan 1 at 9:51
add a comment |
BroadcastReceiver is not for any type of long-running operations (whether synchronous or asynchronously waiting for some callback). It is simply used for receiving some event (broadcast) then handing off any longer-running action to the appropriate component (i.e. Activity or Service).
IntentService is for a long-running, synchronous operation that is handled on another thread. A (foreground) service allows you to more or less act as an invisible Activity. You can await asynchronous callbacks (i.e. the user dismissing the alarm).
You can use this library i have made.
service in background and foreground with it you run service and than receive the call with broadcast
with simple code you start call or start your service like this
RunService service = new RunService(this);
service.call(5);
and do your action inside this method
BroadcastReceiver alarm_receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// your logic here
Log.i("alarm_received", "success");
}
};
dont forget to register the service and remove the service on destroy same as you see in the documentation.
But this dosen't answer my question.
– Ross Lamen
Jan 1 at 9:28
updated my answer
– Hossam Hassan
Jan 1 at 9:33
What I'm asking is should I start a service from a BroadcastReciver or directly call it from an alarm manger. Generally most people call the service from BroadcastReciver. I want to know what is the right practice.
– Ross Lamen
Jan 1 at 9:49
theres no reason at all to call it from broadcast, you should call it directly
– Hossam Hassan
Jan 1 at 9:51
add a comment |
BroadcastReceiver is not for any type of long-running operations (whether synchronous or asynchronously waiting for some callback). It is simply used for receiving some event (broadcast) then handing off any longer-running action to the appropriate component (i.e. Activity or Service).
IntentService is for a long-running, synchronous operation that is handled on another thread. A (foreground) service allows you to more or less act as an invisible Activity. You can await asynchronous callbacks (i.e. the user dismissing the alarm).
You can use this library i have made.
service in background and foreground with it you run service and than receive the call with broadcast
with simple code you start call or start your service like this
RunService service = new RunService(this);
service.call(5);
and do your action inside this method
BroadcastReceiver alarm_receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// your logic here
Log.i("alarm_received", "success");
}
};
dont forget to register the service and remove the service on destroy same as you see in the documentation.
BroadcastReceiver is not for any type of long-running operations (whether synchronous or asynchronously waiting for some callback). It is simply used for receiving some event (broadcast) then handing off any longer-running action to the appropriate component (i.e. Activity or Service).
IntentService is for a long-running, synchronous operation that is handled on another thread. A (foreground) service allows you to more or less act as an invisible Activity. You can await asynchronous callbacks (i.e. the user dismissing the alarm).
You can use this library i have made.
service in background and foreground with it you run service and than receive the call with broadcast
with simple code you start call or start your service like this
RunService service = new RunService(this);
service.call(5);
and do your action inside this method
BroadcastReceiver alarm_receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// your logic here
Log.i("alarm_received", "success");
}
};
dont forget to register the service and remove the service on destroy same as you see in the documentation.
edited Jan 1 at 9:31
answered Jan 1 at 9:25
Hossam HassanHossam Hassan
2471319
2471319
But this dosen't answer my question.
– Ross Lamen
Jan 1 at 9:28
updated my answer
– Hossam Hassan
Jan 1 at 9:33
What I'm asking is should I start a service from a BroadcastReciver or directly call it from an alarm manger. Generally most people call the service from BroadcastReciver. I want to know what is the right practice.
– Ross Lamen
Jan 1 at 9:49
theres no reason at all to call it from broadcast, you should call it directly
– Hossam Hassan
Jan 1 at 9:51
add a comment |
But this dosen't answer my question.
– Ross Lamen
Jan 1 at 9:28
updated my answer
– Hossam Hassan
Jan 1 at 9:33
What I'm asking is should I start a service from a BroadcastReciver or directly call it from an alarm manger. Generally most people call the service from BroadcastReciver. I want to know what is the right practice.
– Ross Lamen
Jan 1 at 9:49
theres no reason at all to call it from broadcast, you should call it directly
– Hossam Hassan
Jan 1 at 9:51
But this dosen't answer my question.
– Ross Lamen
Jan 1 at 9:28
But this dosen't answer my question.
– Ross Lamen
Jan 1 at 9:28
updated my answer
– Hossam Hassan
Jan 1 at 9:33
updated my answer
– Hossam Hassan
Jan 1 at 9:33
What I'm asking is should I start a service from a BroadcastReciver or directly call it from an alarm manger. Generally most people call the service from BroadcastReciver. I want to know what is the right practice.
– Ross Lamen
Jan 1 at 9:49
What I'm asking is should I start a service from a BroadcastReciver or directly call it from an alarm manger. Generally most people call the service from BroadcastReciver. I want to know what is the right practice.
– Ross Lamen
Jan 1 at 9:49
theres no reason at all to call it from broadcast, you should call it directly
– Hossam Hassan
Jan 1 at 9:51
theres no reason at all to call it from broadcast, you should call it directly
– Hossam Hassan
Jan 1 at 9:51
add a comment |
I suggest using Broadcast receiver and when onReceive you can fire service or do anything, also it's useful especially when you need to receive android.intent.action.BOOT_COMPLETED to reschedule your pending alarms because when the device restarted the OS will delete any pending alarms, for more info check this link
add a comment |
I suggest using Broadcast receiver and when onReceive you can fire service or do anything, also it's useful especially when you need to receive android.intent.action.BOOT_COMPLETED to reschedule your pending alarms because when the device restarted the OS will delete any pending alarms, for more info check this link
add a comment |
I suggest using Broadcast receiver and when onReceive you can fire service or do anything, also it's useful especially when you need to receive android.intent.action.BOOT_COMPLETED to reschedule your pending alarms because when the device restarted the OS will delete any pending alarms, for more info check this link
I suggest using Broadcast receiver and when onReceive you can fire service or do anything, also it's useful especially when you need to receive android.intent.action.BOOT_COMPLETED to reschedule your pending alarms because when the device restarted the OS will delete any pending alarms, for more info check this link
answered Jan 1 at 17:48
Ahmed IbrahimAhmed Ibrahim
2112
2112
add a comment |
add a comment |
namespace Diabetes.Droid
{
[Application]
public class MainApplication : Application
{
ISetAlarm alarmService;
public static Context AppContext;
public MainApplication()
{
}
public MainApplication(IntPtr handle, JniHandleOwnership transer) : base(handle, transer)
{
}
public override void OnCreate()
{
base.OnCreate();
AppContext = this.ApplicationContext;
alarmService = new SetAlarmImplementation();
alarmService.SetAlarm(13,58,"hello","great work ");
}
public void SetAlarm(int hour, int minute, string title, string message)
{
AppContext.StartService(new Intent(AppContext, typeof(AppStickyService)));
Intent myintent = new Intent(Android.App.Application.Context, typeof(AppStickyService));
myintent.PutExtra("message", message);
myintent.PutExtra("title", title);
//PendingIntent pendingintent = PendingIntent.GetBroadcast(Android.App.Application.Context, 0, myintent, PendingIntentFlags.UpdateCurrent);
PendingIntent pintent = PendingIntent.GetService(AppContext, 0, new Intent(AppContext, typeof(AppStickyService)), 0);
Java.Util.Date date = new Java.Util.Date();
Java.Util.Calendar cal = Java.Util.Calendar.Instance;
cal.TimeInMillis = Java.Lang.JavaSystem.CurrentTimeMillis();
cal.Set(Java.Util.CalendarField.HourOfDay, hour);
cal.Set(Java.Util.CalendarField.Minute, minute);
cal.Set(Java.Util.CalendarField.Second, 0);
AlarmManager alarmManager = Android.App.Application.Context.GetSystemService(Android.Content.Context.AlarmService) as AlarmManager;
alarmManager.Set(AlarmType.RtcWakeup, cal.TimeInMillis, pintent);
// alarmManager.Cancel(pintent);
}
public void StartService()
{
AppContext.StartService(new Intent(AppContext, typeof(AppStickyService)));
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat)
{
PendingIntent pintent = PendingIntent.GetService(AppContext, 0, new Intent(AppContext, typeof(AppStickyService)), 0);
//AlarmManager alarm = (AlarmManager)AppContext.GetSystemService(Context.AlarmService);
Toast.MakeText(this, "Service started", ToastLength.Long).Show();
//alarm.Cancel(pintent);
}
}
public static void StopService()
{
AppContext.StopService(new Intent(AppContext, typeof(AppStickyService)));
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat)
{
// Toast.MakeText(this,"Service started", ToastLength.Long).Show();
//PendingIntent pintent = PendingIntent.GetService(AppContext, 0, new Intent(AppContext, typeof(AppStickyService)), 0);
// AlarmManager alarm = (AlarmManager)AppContext.GetSystemService(Context.AlarmService);
//alarm.Cancel(pintent);
}
}
}
This is AlarmImplementation.class
public class SetAlarmImplementation : ISetAlarm
{
public SetAlarmImplementation(){}
public void SetAlarm(int hour, int minute, string title, string message)
{
Intent myintent = new Intent(Android.App.Application.Context, typeof(AlarmReceiver));
myintent.PutExtra("message", message);
myintent.PutExtra("title", title);
PendingIntent pendingintent = PendingIntent.GetBroadcast(Android.App.Application.Context, 0, myintent, PendingIntentFlags.UpdateCurrent);
Java.Util.Date date = new Java.Util.Date();
Java.Util.Calendar cal = Java.Util.Calendar.Instance;
cal.TimeInMillis = Java.Lang.JavaSystem.CurrentTimeMillis();
cal.Set(Java.Util.CalendarField.HourOfDay, hour);
cal.Set(Java.Util.CalendarField.Minute, minute);
cal.Set(Java.Util.CalendarField.Second, 0);
AlarmManager alarmManager = Android.App.Application.Context.GetSystemService(Android.Content.Context.AlarmService) as AlarmManager;
alarmManager.Set(AlarmType.RtcWakeup, cal.TimeInMillis, pendingintent);
}
}
This is BroadcastReceiver.class
[BroadcastReceiver]
[IntentFilter(new string { "android.intent.action.BOOT_COMPLETED" }, Priority = (int)IntentFilterPriority.LowPriority)]
public class AlarmReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
var message = intent.GetStringExtra("message");
var title = intent.GetStringExtra("title");
//Show toast here
//Toast.MakeText(context, "Hello it's me ", ToastLength.Short).Show();
var extras = intent.Extras;
if (extras != null && !extras.IsEmpty)
{
NotificationManager manager_ = context.GetSystemService(Context.NotificationService) as NotificationManager;
var notificationId = extras.GetInt("NotificationIdKey", -1);
if (notificationId != -1)
{
manager_.Cancel(notificationId);
}
}
//Create intent for action 1 (TAKE)
var actionIntent1 = new Intent();
actionIntent1.SetAction("ARCHIVE");
var pIntent1 = PendingIntent.GetBroadcast(context, 0, actionIntent1, PendingIntentFlags.CancelCurrent);
//Create intent for action 2 (REPLY)
var actionIntent2 = new Intent();
actionIntent2.SetAction("REPLY");
var pIntent2 = PendingIntent.GetBroadcast(context, 0, actionIntent2, PendingIntentFlags.CancelCurrent);
Intent resultIntent = context.PackageManager.GetLaunchIntentForPackage(context.PackageName);
var contentIntent = PendingIntent.GetActivity(context, 0, resultIntent, PendingIntentFlags.CancelCurrent);
var pending = PendingIntent.GetActivity(context, 0,
resultIntent,
PendingIntentFlags.CancelCurrent);
//seting an alarm
MedicationDatabase db = new MedicationDatabase();
var alarm_list = db.GetAlarmList();
//Debug.WriteLine(" Time -- : "+ m.ToString());
// Instantiate the Big Text style:
Notification.BigTextStyle textStyle = new Notification.BigTextStyle();
var builder =
new Notification.Builder(context)
.AddAction(Resource.Drawable.tick_notify, "ARCHIVE", pIntent1)
.AddAction(Resource.Drawable.cancel_notify, "REPLY", pIntent2)
.SetSmallIcon(Resource.Drawable.ic_launcher)
.SetContentTitle("Diabetics Reminder")
.SetDefaults(NotificationDefaults.Sound)
.SetStyle(new Notification
.BigTextStyle()
.SetSummaryText("")
.SetBigContentTitle(title)
.BigText(message)
).SetDefaults(NotificationDefaults.All);
builder.SetContentIntent(pending);
var notification = builder.Build();
var manager = NotificationManager.FromContext(context);
manager.Notify(10010, notification);
}
}
and this is the final service class
[Service]
public class AppStickyService : Service
{
public override void OnCreate()
{
base.OnCreate();
// Toast.MakeText(this, "Service started Habiibi", ToastLength.Long).Show();
//WireAlarm();
System.Diagnostics.Debug.WriteLine("Sticky Service - Created");
}
public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId)
{
SetAlarm(12,39,"Try","Start Service");
return StartCommandResult.Sticky;
}
public override Android.OS.IBinder OnBind(Android.Content.Intent intent)
{
System.Diagnostics.Debug.WriteLine("Sticky Service - Binded");
//WireAlarm();
return null;
}
public override void OnDestroy()
{
System.Diagnostics.Debug.WriteLine("Sticky Service - Destroyed");
base.OnDestroy();
WireAlarm();
}
can you elaborate more on the answer?
– Moshe Slavin
Jan 1 at 9:16
this code to be having a sticky service as in when the Application is Idle or sleeping it makes a notification.
– deepak sharma
Jan 1 at 9:26
add a comment |
namespace Diabetes.Droid
{
[Application]
public class MainApplication : Application
{
ISetAlarm alarmService;
public static Context AppContext;
public MainApplication()
{
}
public MainApplication(IntPtr handle, JniHandleOwnership transer) : base(handle, transer)
{
}
public override void OnCreate()
{
base.OnCreate();
AppContext = this.ApplicationContext;
alarmService = new SetAlarmImplementation();
alarmService.SetAlarm(13,58,"hello","great work ");
}
public void SetAlarm(int hour, int minute, string title, string message)
{
AppContext.StartService(new Intent(AppContext, typeof(AppStickyService)));
Intent myintent = new Intent(Android.App.Application.Context, typeof(AppStickyService));
myintent.PutExtra("message", message);
myintent.PutExtra("title", title);
//PendingIntent pendingintent = PendingIntent.GetBroadcast(Android.App.Application.Context, 0, myintent, PendingIntentFlags.UpdateCurrent);
PendingIntent pintent = PendingIntent.GetService(AppContext, 0, new Intent(AppContext, typeof(AppStickyService)), 0);
Java.Util.Date date = new Java.Util.Date();
Java.Util.Calendar cal = Java.Util.Calendar.Instance;
cal.TimeInMillis = Java.Lang.JavaSystem.CurrentTimeMillis();
cal.Set(Java.Util.CalendarField.HourOfDay, hour);
cal.Set(Java.Util.CalendarField.Minute, minute);
cal.Set(Java.Util.CalendarField.Second, 0);
AlarmManager alarmManager = Android.App.Application.Context.GetSystemService(Android.Content.Context.AlarmService) as AlarmManager;
alarmManager.Set(AlarmType.RtcWakeup, cal.TimeInMillis, pintent);
// alarmManager.Cancel(pintent);
}
public void StartService()
{
AppContext.StartService(new Intent(AppContext, typeof(AppStickyService)));
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat)
{
PendingIntent pintent = PendingIntent.GetService(AppContext, 0, new Intent(AppContext, typeof(AppStickyService)), 0);
//AlarmManager alarm = (AlarmManager)AppContext.GetSystemService(Context.AlarmService);
Toast.MakeText(this, "Service started", ToastLength.Long).Show();
//alarm.Cancel(pintent);
}
}
public static void StopService()
{
AppContext.StopService(new Intent(AppContext, typeof(AppStickyService)));
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat)
{
// Toast.MakeText(this,"Service started", ToastLength.Long).Show();
//PendingIntent pintent = PendingIntent.GetService(AppContext, 0, new Intent(AppContext, typeof(AppStickyService)), 0);
// AlarmManager alarm = (AlarmManager)AppContext.GetSystemService(Context.AlarmService);
//alarm.Cancel(pintent);
}
}
}
This is AlarmImplementation.class
public class SetAlarmImplementation : ISetAlarm
{
public SetAlarmImplementation(){}
public void SetAlarm(int hour, int minute, string title, string message)
{
Intent myintent = new Intent(Android.App.Application.Context, typeof(AlarmReceiver));
myintent.PutExtra("message", message);
myintent.PutExtra("title", title);
PendingIntent pendingintent = PendingIntent.GetBroadcast(Android.App.Application.Context, 0, myintent, PendingIntentFlags.UpdateCurrent);
Java.Util.Date date = new Java.Util.Date();
Java.Util.Calendar cal = Java.Util.Calendar.Instance;
cal.TimeInMillis = Java.Lang.JavaSystem.CurrentTimeMillis();
cal.Set(Java.Util.CalendarField.HourOfDay, hour);
cal.Set(Java.Util.CalendarField.Minute, minute);
cal.Set(Java.Util.CalendarField.Second, 0);
AlarmManager alarmManager = Android.App.Application.Context.GetSystemService(Android.Content.Context.AlarmService) as AlarmManager;
alarmManager.Set(AlarmType.RtcWakeup, cal.TimeInMillis, pendingintent);
}
}
This is BroadcastReceiver.class
[BroadcastReceiver]
[IntentFilter(new string { "android.intent.action.BOOT_COMPLETED" }, Priority = (int)IntentFilterPriority.LowPriority)]
public class AlarmReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
var message = intent.GetStringExtra("message");
var title = intent.GetStringExtra("title");
//Show toast here
//Toast.MakeText(context, "Hello it's me ", ToastLength.Short).Show();
var extras = intent.Extras;
if (extras != null && !extras.IsEmpty)
{
NotificationManager manager_ = context.GetSystemService(Context.NotificationService) as NotificationManager;
var notificationId = extras.GetInt("NotificationIdKey", -1);
if (notificationId != -1)
{
manager_.Cancel(notificationId);
}
}
//Create intent for action 1 (TAKE)
var actionIntent1 = new Intent();
actionIntent1.SetAction("ARCHIVE");
var pIntent1 = PendingIntent.GetBroadcast(context, 0, actionIntent1, PendingIntentFlags.CancelCurrent);
//Create intent for action 2 (REPLY)
var actionIntent2 = new Intent();
actionIntent2.SetAction("REPLY");
var pIntent2 = PendingIntent.GetBroadcast(context, 0, actionIntent2, PendingIntentFlags.CancelCurrent);
Intent resultIntent = context.PackageManager.GetLaunchIntentForPackage(context.PackageName);
var contentIntent = PendingIntent.GetActivity(context, 0, resultIntent, PendingIntentFlags.CancelCurrent);
var pending = PendingIntent.GetActivity(context, 0,
resultIntent,
PendingIntentFlags.CancelCurrent);
//seting an alarm
MedicationDatabase db = new MedicationDatabase();
var alarm_list = db.GetAlarmList();
//Debug.WriteLine(" Time -- : "+ m.ToString());
// Instantiate the Big Text style:
Notification.BigTextStyle textStyle = new Notification.BigTextStyle();
var builder =
new Notification.Builder(context)
.AddAction(Resource.Drawable.tick_notify, "ARCHIVE", pIntent1)
.AddAction(Resource.Drawable.cancel_notify, "REPLY", pIntent2)
.SetSmallIcon(Resource.Drawable.ic_launcher)
.SetContentTitle("Diabetics Reminder")
.SetDefaults(NotificationDefaults.Sound)
.SetStyle(new Notification
.BigTextStyle()
.SetSummaryText("")
.SetBigContentTitle(title)
.BigText(message)
).SetDefaults(NotificationDefaults.All);
builder.SetContentIntent(pending);
var notification = builder.Build();
var manager = NotificationManager.FromContext(context);
manager.Notify(10010, notification);
}
}
and this is the final service class
[Service]
public class AppStickyService : Service
{
public override void OnCreate()
{
base.OnCreate();
// Toast.MakeText(this, "Service started Habiibi", ToastLength.Long).Show();
//WireAlarm();
System.Diagnostics.Debug.WriteLine("Sticky Service - Created");
}
public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId)
{
SetAlarm(12,39,"Try","Start Service");
return StartCommandResult.Sticky;
}
public override Android.OS.IBinder OnBind(Android.Content.Intent intent)
{
System.Diagnostics.Debug.WriteLine("Sticky Service - Binded");
//WireAlarm();
return null;
}
public override void OnDestroy()
{
System.Diagnostics.Debug.WriteLine("Sticky Service - Destroyed");
base.OnDestroy();
WireAlarm();
}
can you elaborate more on the answer?
– Moshe Slavin
Jan 1 at 9:16
this code to be having a sticky service as in when the Application is Idle or sleeping it makes a notification.
– deepak sharma
Jan 1 at 9:26
add a comment |
namespace Diabetes.Droid
{
[Application]
public class MainApplication : Application
{
ISetAlarm alarmService;
public static Context AppContext;
public MainApplication()
{
}
public MainApplication(IntPtr handle, JniHandleOwnership transer) : base(handle, transer)
{
}
public override void OnCreate()
{
base.OnCreate();
AppContext = this.ApplicationContext;
alarmService = new SetAlarmImplementation();
alarmService.SetAlarm(13,58,"hello","great work ");
}
public void SetAlarm(int hour, int minute, string title, string message)
{
AppContext.StartService(new Intent(AppContext, typeof(AppStickyService)));
Intent myintent = new Intent(Android.App.Application.Context, typeof(AppStickyService));
myintent.PutExtra("message", message);
myintent.PutExtra("title", title);
//PendingIntent pendingintent = PendingIntent.GetBroadcast(Android.App.Application.Context, 0, myintent, PendingIntentFlags.UpdateCurrent);
PendingIntent pintent = PendingIntent.GetService(AppContext, 0, new Intent(AppContext, typeof(AppStickyService)), 0);
Java.Util.Date date = new Java.Util.Date();
Java.Util.Calendar cal = Java.Util.Calendar.Instance;
cal.TimeInMillis = Java.Lang.JavaSystem.CurrentTimeMillis();
cal.Set(Java.Util.CalendarField.HourOfDay, hour);
cal.Set(Java.Util.CalendarField.Minute, minute);
cal.Set(Java.Util.CalendarField.Second, 0);
AlarmManager alarmManager = Android.App.Application.Context.GetSystemService(Android.Content.Context.AlarmService) as AlarmManager;
alarmManager.Set(AlarmType.RtcWakeup, cal.TimeInMillis, pintent);
// alarmManager.Cancel(pintent);
}
public void StartService()
{
AppContext.StartService(new Intent(AppContext, typeof(AppStickyService)));
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat)
{
PendingIntent pintent = PendingIntent.GetService(AppContext, 0, new Intent(AppContext, typeof(AppStickyService)), 0);
//AlarmManager alarm = (AlarmManager)AppContext.GetSystemService(Context.AlarmService);
Toast.MakeText(this, "Service started", ToastLength.Long).Show();
//alarm.Cancel(pintent);
}
}
public static void StopService()
{
AppContext.StopService(new Intent(AppContext, typeof(AppStickyService)));
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat)
{
// Toast.MakeText(this,"Service started", ToastLength.Long).Show();
//PendingIntent pintent = PendingIntent.GetService(AppContext, 0, new Intent(AppContext, typeof(AppStickyService)), 0);
// AlarmManager alarm = (AlarmManager)AppContext.GetSystemService(Context.AlarmService);
//alarm.Cancel(pintent);
}
}
}
This is AlarmImplementation.class
public class SetAlarmImplementation : ISetAlarm
{
public SetAlarmImplementation(){}
public void SetAlarm(int hour, int minute, string title, string message)
{
Intent myintent = new Intent(Android.App.Application.Context, typeof(AlarmReceiver));
myintent.PutExtra("message", message);
myintent.PutExtra("title", title);
PendingIntent pendingintent = PendingIntent.GetBroadcast(Android.App.Application.Context, 0, myintent, PendingIntentFlags.UpdateCurrent);
Java.Util.Date date = new Java.Util.Date();
Java.Util.Calendar cal = Java.Util.Calendar.Instance;
cal.TimeInMillis = Java.Lang.JavaSystem.CurrentTimeMillis();
cal.Set(Java.Util.CalendarField.HourOfDay, hour);
cal.Set(Java.Util.CalendarField.Minute, minute);
cal.Set(Java.Util.CalendarField.Second, 0);
AlarmManager alarmManager = Android.App.Application.Context.GetSystemService(Android.Content.Context.AlarmService) as AlarmManager;
alarmManager.Set(AlarmType.RtcWakeup, cal.TimeInMillis, pendingintent);
}
}
This is BroadcastReceiver.class
[BroadcastReceiver]
[IntentFilter(new string { "android.intent.action.BOOT_COMPLETED" }, Priority = (int)IntentFilterPriority.LowPriority)]
public class AlarmReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
var message = intent.GetStringExtra("message");
var title = intent.GetStringExtra("title");
//Show toast here
//Toast.MakeText(context, "Hello it's me ", ToastLength.Short).Show();
var extras = intent.Extras;
if (extras != null && !extras.IsEmpty)
{
NotificationManager manager_ = context.GetSystemService(Context.NotificationService) as NotificationManager;
var notificationId = extras.GetInt("NotificationIdKey", -1);
if (notificationId != -1)
{
manager_.Cancel(notificationId);
}
}
//Create intent for action 1 (TAKE)
var actionIntent1 = new Intent();
actionIntent1.SetAction("ARCHIVE");
var pIntent1 = PendingIntent.GetBroadcast(context, 0, actionIntent1, PendingIntentFlags.CancelCurrent);
//Create intent for action 2 (REPLY)
var actionIntent2 = new Intent();
actionIntent2.SetAction("REPLY");
var pIntent2 = PendingIntent.GetBroadcast(context, 0, actionIntent2, PendingIntentFlags.CancelCurrent);
Intent resultIntent = context.PackageManager.GetLaunchIntentForPackage(context.PackageName);
var contentIntent = PendingIntent.GetActivity(context, 0, resultIntent, PendingIntentFlags.CancelCurrent);
var pending = PendingIntent.GetActivity(context, 0,
resultIntent,
PendingIntentFlags.CancelCurrent);
//seting an alarm
MedicationDatabase db = new MedicationDatabase();
var alarm_list = db.GetAlarmList();
//Debug.WriteLine(" Time -- : "+ m.ToString());
// Instantiate the Big Text style:
Notification.BigTextStyle textStyle = new Notification.BigTextStyle();
var builder =
new Notification.Builder(context)
.AddAction(Resource.Drawable.tick_notify, "ARCHIVE", pIntent1)
.AddAction(Resource.Drawable.cancel_notify, "REPLY", pIntent2)
.SetSmallIcon(Resource.Drawable.ic_launcher)
.SetContentTitle("Diabetics Reminder")
.SetDefaults(NotificationDefaults.Sound)
.SetStyle(new Notification
.BigTextStyle()
.SetSummaryText("")
.SetBigContentTitle(title)
.BigText(message)
).SetDefaults(NotificationDefaults.All);
builder.SetContentIntent(pending);
var notification = builder.Build();
var manager = NotificationManager.FromContext(context);
manager.Notify(10010, notification);
}
}
and this is the final service class
[Service]
public class AppStickyService : Service
{
public override void OnCreate()
{
base.OnCreate();
// Toast.MakeText(this, "Service started Habiibi", ToastLength.Long).Show();
//WireAlarm();
System.Diagnostics.Debug.WriteLine("Sticky Service - Created");
}
public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId)
{
SetAlarm(12,39,"Try","Start Service");
return StartCommandResult.Sticky;
}
public override Android.OS.IBinder OnBind(Android.Content.Intent intent)
{
System.Diagnostics.Debug.WriteLine("Sticky Service - Binded");
//WireAlarm();
return null;
}
public override void OnDestroy()
{
System.Diagnostics.Debug.WriteLine("Sticky Service - Destroyed");
base.OnDestroy();
WireAlarm();
}
namespace Diabetes.Droid
{
[Application]
public class MainApplication : Application
{
ISetAlarm alarmService;
public static Context AppContext;
public MainApplication()
{
}
public MainApplication(IntPtr handle, JniHandleOwnership transer) : base(handle, transer)
{
}
public override void OnCreate()
{
base.OnCreate();
AppContext = this.ApplicationContext;
alarmService = new SetAlarmImplementation();
alarmService.SetAlarm(13,58,"hello","great work ");
}
public void SetAlarm(int hour, int minute, string title, string message)
{
AppContext.StartService(new Intent(AppContext, typeof(AppStickyService)));
Intent myintent = new Intent(Android.App.Application.Context, typeof(AppStickyService));
myintent.PutExtra("message", message);
myintent.PutExtra("title", title);
//PendingIntent pendingintent = PendingIntent.GetBroadcast(Android.App.Application.Context, 0, myintent, PendingIntentFlags.UpdateCurrent);
PendingIntent pintent = PendingIntent.GetService(AppContext, 0, new Intent(AppContext, typeof(AppStickyService)), 0);
Java.Util.Date date = new Java.Util.Date();
Java.Util.Calendar cal = Java.Util.Calendar.Instance;
cal.TimeInMillis = Java.Lang.JavaSystem.CurrentTimeMillis();
cal.Set(Java.Util.CalendarField.HourOfDay, hour);
cal.Set(Java.Util.CalendarField.Minute, minute);
cal.Set(Java.Util.CalendarField.Second, 0);
AlarmManager alarmManager = Android.App.Application.Context.GetSystemService(Android.Content.Context.AlarmService) as AlarmManager;
alarmManager.Set(AlarmType.RtcWakeup, cal.TimeInMillis, pintent);
// alarmManager.Cancel(pintent);
}
public void StartService()
{
AppContext.StartService(new Intent(AppContext, typeof(AppStickyService)));
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat)
{
PendingIntent pintent = PendingIntent.GetService(AppContext, 0, new Intent(AppContext, typeof(AppStickyService)), 0);
//AlarmManager alarm = (AlarmManager)AppContext.GetSystemService(Context.AlarmService);
Toast.MakeText(this, "Service started", ToastLength.Long).Show();
//alarm.Cancel(pintent);
}
}
public static void StopService()
{
AppContext.StopService(new Intent(AppContext, typeof(AppStickyService)));
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat)
{
// Toast.MakeText(this,"Service started", ToastLength.Long).Show();
//PendingIntent pintent = PendingIntent.GetService(AppContext, 0, new Intent(AppContext, typeof(AppStickyService)), 0);
// AlarmManager alarm = (AlarmManager)AppContext.GetSystemService(Context.AlarmService);
//alarm.Cancel(pintent);
}
}
}
This is AlarmImplementation.class
public class SetAlarmImplementation : ISetAlarm
{
public SetAlarmImplementation(){}
public void SetAlarm(int hour, int minute, string title, string message)
{
Intent myintent = new Intent(Android.App.Application.Context, typeof(AlarmReceiver));
myintent.PutExtra("message", message);
myintent.PutExtra("title", title);
PendingIntent pendingintent = PendingIntent.GetBroadcast(Android.App.Application.Context, 0, myintent, PendingIntentFlags.UpdateCurrent);
Java.Util.Date date = new Java.Util.Date();
Java.Util.Calendar cal = Java.Util.Calendar.Instance;
cal.TimeInMillis = Java.Lang.JavaSystem.CurrentTimeMillis();
cal.Set(Java.Util.CalendarField.HourOfDay, hour);
cal.Set(Java.Util.CalendarField.Minute, minute);
cal.Set(Java.Util.CalendarField.Second, 0);
AlarmManager alarmManager = Android.App.Application.Context.GetSystemService(Android.Content.Context.AlarmService) as AlarmManager;
alarmManager.Set(AlarmType.RtcWakeup, cal.TimeInMillis, pendingintent);
}
}
This is BroadcastReceiver.class
[BroadcastReceiver]
[IntentFilter(new string { "android.intent.action.BOOT_COMPLETED" }, Priority = (int)IntentFilterPriority.LowPriority)]
public class AlarmReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
var message = intent.GetStringExtra("message");
var title = intent.GetStringExtra("title");
//Show toast here
//Toast.MakeText(context, "Hello it's me ", ToastLength.Short).Show();
var extras = intent.Extras;
if (extras != null && !extras.IsEmpty)
{
NotificationManager manager_ = context.GetSystemService(Context.NotificationService) as NotificationManager;
var notificationId = extras.GetInt("NotificationIdKey", -1);
if (notificationId != -1)
{
manager_.Cancel(notificationId);
}
}
//Create intent for action 1 (TAKE)
var actionIntent1 = new Intent();
actionIntent1.SetAction("ARCHIVE");
var pIntent1 = PendingIntent.GetBroadcast(context, 0, actionIntent1, PendingIntentFlags.CancelCurrent);
//Create intent for action 2 (REPLY)
var actionIntent2 = new Intent();
actionIntent2.SetAction("REPLY");
var pIntent2 = PendingIntent.GetBroadcast(context, 0, actionIntent2, PendingIntentFlags.CancelCurrent);
Intent resultIntent = context.PackageManager.GetLaunchIntentForPackage(context.PackageName);
var contentIntent = PendingIntent.GetActivity(context, 0, resultIntent, PendingIntentFlags.CancelCurrent);
var pending = PendingIntent.GetActivity(context, 0,
resultIntent,
PendingIntentFlags.CancelCurrent);
//seting an alarm
MedicationDatabase db = new MedicationDatabase();
var alarm_list = db.GetAlarmList();
//Debug.WriteLine(" Time -- : "+ m.ToString());
// Instantiate the Big Text style:
Notification.BigTextStyle textStyle = new Notification.BigTextStyle();
var builder =
new Notification.Builder(context)
.AddAction(Resource.Drawable.tick_notify, "ARCHIVE", pIntent1)
.AddAction(Resource.Drawable.cancel_notify, "REPLY", pIntent2)
.SetSmallIcon(Resource.Drawable.ic_launcher)
.SetContentTitle("Diabetics Reminder")
.SetDefaults(NotificationDefaults.Sound)
.SetStyle(new Notification
.BigTextStyle()
.SetSummaryText("")
.SetBigContentTitle(title)
.BigText(message)
).SetDefaults(NotificationDefaults.All);
builder.SetContentIntent(pending);
var notification = builder.Build();
var manager = NotificationManager.FromContext(context);
manager.Notify(10010, notification);
}
}
and this is the final service class
[Service]
public class AppStickyService : Service
{
public override void OnCreate()
{
base.OnCreate();
// Toast.MakeText(this, "Service started Habiibi", ToastLength.Long).Show();
//WireAlarm();
System.Diagnostics.Debug.WriteLine("Sticky Service - Created");
}
public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId)
{
SetAlarm(12,39,"Try","Start Service");
return StartCommandResult.Sticky;
}
public override Android.OS.IBinder OnBind(Android.Content.Intent intent)
{
System.Diagnostics.Debug.WriteLine("Sticky Service - Binded");
//WireAlarm();
return null;
}
public override void OnDestroy()
{
System.Diagnostics.Debug.WriteLine("Sticky Service - Destroyed");
base.OnDestroy();
WireAlarm();
}
edited Jan 1 at 9:19
answered Jan 1 at 9:13
deepak sharmadeepak sharma
11
11
can you elaborate more on the answer?
– Moshe Slavin
Jan 1 at 9:16
this code to be having a sticky service as in when the Application is Idle or sleeping it makes a notification.
– deepak sharma
Jan 1 at 9:26
add a comment |
can you elaborate more on the answer?
– Moshe Slavin
Jan 1 at 9:16
this code to be having a sticky service as in when the Application is Idle or sleeping it makes a notification.
– deepak sharma
Jan 1 at 9:26
can you elaborate more on the answer?
– Moshe Slavin
Jan 1 at 9:16
can you elaborate more on the answer?
– Moshe Slavin
Jan 1 at 9:16
this code to be having a sticky service as in when the Application is Idle or sleeping it makes a notification.
– deepak sharma
Jan 1 at 9:26
this code to be having a sticky service as in when the Application is Idle or sleeping it makes a notification.
– deepak sharma
Jan 1 at 9:26
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53994093%2fshould-i-use-broadcastreciver-or-service-with-alarm-manager%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
honestly i dont see any difference if your
Intentpoints to aServiceorBroadcastReceiver- but you could check WorkManager sources and see how they do that– pskink
Jan 1 at 10:00
this one
androidx/work/impl/background/systemalarm/SystemAlarmService.javain particular - it is executed fromandroidx/work/impl/background/systemalarm/Alarms.java– pskink
Jan 1 at 10:19