简体   繁体   中英

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. I want a toast message to appear each 5 seconds while the service in running. 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 ?

I want a toast message to appear each 5 seconds while the service in running. The following code does not seem to be doing the job

Once OnStartCommand finish executing, DoWork won't execute any more.

According to your requirement, you need to use JobScheduler together with JobInfo to create a periodic task. For how to use JobScheduler, You can refer to the official demo of JobScheduler

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