Monday 19 September 2016

How to Schedule Notification in Android using Xamarin - Part3 (BOOT_COMPLETED and DontKillApp)

"Restart device will basically clear all the pending intent set previously. "

I found this sentence from one of the article in stack overflow. From there, I discovered the usage of 'BOOT_COMPLETED' and 'DontKillApp'. I am not 100% sure the original usage or even the definition to both of them. But, I think I can use it on my case after the result of few experiments.

Well, all my previous example of 'How to schedule notification in Android using Xamarin' were actually triggered by the button clicked event. Of course, you may argue I can actually move the logic to one of the override / start event of the app, so that it will fire or call the method when the app start.

"The keyword is 'app start'"...
Instead, what we want is when the device finished its booting process, not app start.
In many cases, we need to perform some task when device finished its batting process. For example: show notification that 'SIM has been changed', etc. For this kind of scenario, we need Broadcast receiver that should receiver "BOOT_COMPLETED" broadcast. We must know that when a device finishes booting android system sends 'BOOT_COMPLETED' broadcast.

Permission: ReceivedBootCompleted in Xamarin.
IntentFilter: [IntentFilter(new[] {"android.intent.action.BOOT_COMPLETED"})]

Filter to look for this intent only.


Example of using BOOT_COMPLETED
I created a class named 'BootReceiver' that extended from BroadcastReceiver.  As long as you have the right permission set, plus the correct attribute set in the class. The OnReceive() method will be called when the device finish the booting process. 
Sample source code:
[BroadcastReceiver (Enabled = true)]
    [IntentFilter(new[] {"android.intent.action.BOOT_COMPLETED"})]
    public class BootReceiver : BroadcastReceiver
    {
        
        public override void OnReceive(Context context, Intent intent)
        {
            var alarmIntent = new Intent(context, typeof(AlarmReceiver));
            var pending = PendingIntent.GetBroadcast(context, 0, alarmIntent, PendingIntentFlags.CancelCurrent);


            AlarmManager alertManager = (AlarmManager)context.GetSystemService(Context.AlarmService);
            Console.WriteLine("SystemClock.ElapsedRealtime() : " + SystemClock.ElapsedRealtime().ToString());
            alertManager.Set(AlarmType.ElapsedRealtime, SystemClock.ElapsedRealtime() + 1 * 1000, pending);
        }
    }
 








1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete

How to run unit test for your Xamarin Application in AppCenter?

How to run unit test for your Xamarin application in AppCenter?  When we talk about Building and Distributing your Xamarin app, you m...