简体   繁体   English

Xamarin.Android中的重复后台任务

[英]Recurring background task in Xamarin.Android

I would like to write a silence/vibration scheduler for Android 6. 我想为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. 因此,我需要一个后台任务,该任务根据已完成并准备就绪的UI应用程序中定义的时间表来设置声音/振动/静音。

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. 我可以使用AudioManager来读取/设置值,但是我不知道如何安排任务。

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. 将Android.Content.Intent设置为ActionTimeTick,以便每当时间更改时android os都会广播消息(一个android intent)。

[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. 将这些代码添加到oncreate方法中以注册广播接收器。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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