简体   繁体   English

在Xamarin.android中的后台服务中每五秒钟显示一次吐司消息

[英]Show a toast message after each five seconds in Background Service in Xamarin.android

I have implemented a background service. 我已经实施了后台服务。 When I boot my device, the background service is started and toast message is displayed. 当我启动设备时,将启动后台服务,并显示Toast消息。 I want a toast message to appear each 5 seconds while the service in running. 我希望在运行服务时每5秒显示一条祝酒消息。 The following code does not seem to be doing the job: 以下代码似乎没有完成这项工作:

[Service]
    public class BroadcastService : Service
    {
        IBinder mBinder;

        [return: GeneratedEnum]
        public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
        {

            Toast.MakeText(this, "BroadcastService Started...", ToastLength.Long).Show();

            DoWork();

            base.OnStartCommand(intent, flags, startId);
            return StartCommandResult.Sticky;


        }

public void DoWork()
{
    while (true)
    {
        Toast.MakeText(this, "BroadcastService is running at each 5 seconds...", ToastLength.Long).Show();
        Thread.Sleep(5000);
    }
}

Can somebody please advise what is wrong above and help to achieve this in Xamarin.android ? 有人可以建议上面的问题是什么,并帮助在Xamarin.android中实现吗?

I want a toast message to appear each 5 seconds while the service in running. 我希望在运行服务时每5秒显示一条祝酒消息。 The following code does not seem to be doing the job 以下代码似乎没有完成任务

Once OnStartCommand finish executing, DoWork won't execute any more. 一旦OnStartCommand完成执行, DoWork将不再执行。

According to your requirement, you need to use JobScheduler together with JobInfo to create a periodic task. 根据您的要求,您需要结合使用JobSchedulerJobInfo来创建定期任务。 For how to use JobScheduler, You can refer to the official demo of JobScheduler 有关如何使用JobScheduler的信息,请参阅JobScheduler官方演示。

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

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