Schedule notification using alarm manager in xamarin forms for android

不问归期 提交于 2019-11-30 13:05:06

1) If someone kills your app, alarms registered to your app are cancelled.

2) You can start your service in the background on Boot of the device in order to register your alarms, or run any other code you need to setup your notifications...

  • Add "android.intent.action.BOOT_COMPLETED" to your BroadcastReceiver:

[BroadcastReceiver]
[IntentFilter(new string[]{"android.intent.action.BOOT_COMPLETED"}, Priority = (int)IntentFilterPriority.LowPriority)]
public class AlarmReceiver : BroadcastReceiver

  • In your manifest add in the boot complete permission:

<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>    

In the case of Xamarin's Stock Price example, if you set "RECEIVE_BOOT_COMPLETED" you are "auto" restart your service and the your will start receiving notifications upon reboot of their phone without first launching your app:

[BroadcastReceiver]
[IntentFilter(new string[]{StockService.StocksUpdatedAction,Boo "android.intent.action.BOOT_COMPLETED"}, Priority = (int)IntentFilterPriority.LowPriority)]
public class StockNotificationReceiver : BroadcastReceiver

3) You can use a Service vs. a SeviceIntent and override the StartCommandResult to return Sticky

With a Sticky-based Service, it is restarted if it gets terminated.

Constant to return from onStartCommand(Intent, int, int): if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service. Because it is in the started state, it will guarantee to call onStartCommand(Intent, int, int) after creating the new service instance; if there are not any pending start commands to be delivered to the service, it will be called with a null intent object, so you must take care to check for this.

    public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
    {
        return StartCommandResult.Sticky;
    }
Sreeraj

AlarmManager will work when the App is running in Foreground or in Background. But when the App is quit/force-stopped/killed Alarm Manager is also killed. Alarm will go off again only if Android is Re-booted or App is again launched by the user. Check these answers also for reference link1 , link2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!