简体   繁体   中英

Recurring background task in Xamarin.Android

I would like to write a silence/vibration scheduler for Android 6.

I need therefore a background task that sets sound/vibration/silence according to a schedule defined in the UI app which is done and ready.

How can I add such a service to my application to run in the background? (recurring service that checks/sets ringtone status on a minute basis)

I can use the AudioManager to read/set the value, but I do not know how to schedule the task.

You need to add a broadcast receiver for these. Set Android.Content.Intent to ActionTimeTick so that android os will broadcast message(an android intent) whenever time is changed.

[BroadcastReceiver(Enabled = true)]
    [IntentFilter(new[] { Android.Content.Intent.ActionTimeTick })]
    public class GridStartBroadcastReceiver : BroadcastReceiver
    {
        public static readonly string GRID_STARTED = "GRID_STARTED";
        public override void OnReceive(Context context, Intent intent)
        {
           if (intent.Action == GRID_STARTED)
            {
         //your logic
            }
        }
    }

you need to register the broadcast receiver first. Add these code to oncreate method to register broadcast receiver.

IntentFilter filter = new IntentFilter(GridStartBroadcastReceiver.GRID_STARTED); filter.AddCategory(Intent.CategoryDefault); _receiver = new GridStartBroadcastReceiver(); RegisterReceiver(_receiver, filter);

Next send the broadcast to the broadcast receiver.

//calling
                    Intent BroadcastIntent = new Intent(this, typeof(MainActivity.GridStartBroadcastReceiver));
                    BroadcastIntent.SetAction(MainActivity.GridStartBroadcastReceiver.GRID_STARTED);
                    BroadcastIntent.AddCategory(Intent.CategoryDefault);
                    SendBroadcast(BroadcastIntent);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM