Return results from Background service

Hi All,
Am newbie to xamarin.android currently i have a requirement where i have to keep receving messages from a third party server via wss protocol. So, am running a background service where i have scheduled a job for every twelve seconds, am connecting to third party server and receiving messages via wss protocol. But, am unable to process that message within application. The method does not return if i try to return a string message. I have tried registering an explicit broadcast receiver to process the message. But, its unreliable sometimes it overrides onReceive where as most of the times it does not even override. Please suggest some solution. Following is the code

Action myAction = async () =>
{
await connectToServer.ReadNotificationServer();

            };

handler.PostDelayed(myAction, 12000);
Am calling this method within OnStartCommand, ReadNotification server method reads the message from WSS protocol. But, not able to register receiver. I can provide further elaboration.

Answers

  • JarvanJarvan Member, Xamarin Team Xamurai

    have a requirement where i have to keep receving messages from...

    To schedule background work, try using the Android Job Scheduler API. The Android Job Scheduler is a framework built in to the Android operating system that provides a fluent API to simplify scheduling background work. To schedule work with the Android Job Scheduler, Xamarin.Android application must encapsulate the code in a class that extends the JobService class.

    [Service(Name = "com.xamarin.samples.downloadscheduler.DownloadJob", 
             Permission = "android.permission.BIND_JOB_SERVICE")]
    public class DownloadJob : JobService
    {
        public override bool OnStartJob(JobParameters jobParams)
        {            
            Task.Run(() =>
            {
                // Work is happening asynchronously
    
                // Have to tell the JobScheduler the work is done. 
                JobFinished(jobParams, false);
            });
    
            // Return true because of the asynchronous work
            return true;  
        }
    
        public override bool OnStopJob(JobParameters jobParams)
        {
            // we don't want to reschedule the job if it is stopped or cancelled.
            return false; 
        }
    }
    

    For more detials, check the tutorial:
    https://docs.microsoft.com/en-us/xamarin/android/platform/android-job-scheduler

Sign In or Register to comment.