0

I have an Android Xamarin app that handles notifications. When a notification is displayed, there are buttons that ask for a response. The app needs to send this response back to a server via an httpClient.PostAsync call. I am using the same http client wrapper in other parts of the code and it is working correctly. However, when I call it from the JobService code, the app crashes. I have enclosed the http call in a try/catch and no exception occurs. There are also no errors in the device log. i would like to know how to debug this. Here is my flow:

I have a class that derives from FirebaseMessagingService with an OnMessageReceived method. That gets called when a notification arrives. I build a local notification via the notification manager and call .Notify. The notification appears with the buttons. I have a BroadcastReceiver with an OnReceive method. That method schedules a job to do the post back of the button click. The job gets started and runs until the point I call the PostAsync. From there it crashes with no exception. Here is the relevant part of the JobWorker:

        public override bool OnStartJob(JobParameters jobParams)
        {
            _backgroundWorker = Task.Run(() => { DoWork(jobParams); });
            return true;
        }

        private void DoWork(JobParameters jobParams)
        {
            var logger = App.ResolveDependency<ILogger>() as ILogger;
            var callActions = App.ResolveDependency<ICallActionsHandler>() as ICallActionsHandler;

            var callToken = jobParams.Extras.GetString(JobParameterCallToken);
            var subsciberPhoneNumber = jobParams.Extras.GetString(JobParameterSubscriberPhoneNumber);
            var action = jobParams.Extras.GetString(JobParametersCallAction);

            logger.TraceInfo($"starting {nameof(CallActionService)}: starting job {jobParams.JobId}");
            callActions.SendAction(
                callToken,
                subsciberPhoneNumber,
                (CallActions)Enum.Parse(typeof(CallActions), action));
        }

The SendAction code calls the http client wrapper. The http client wrapper code looks like this:

        public async Task<int> PostAsync(string api, object message)
        {
            var apiUrl = Constants.DefaultAppApi + api;
            var contentText = JsonConvert.SerializeObject(message);
            var content = new StringContent(contentText, Encoding.UTF8, "application/json");
            var backOff = 10;
            var retryCount = 5;
            HttpResponseMessage response = null;

            for (var attempt = 1; attempt <= retryCount; attempt++)
            {
                _logger.TraceInfo($"DataServerClient Post message: {message.GetType().Name}, attempt = {attempt}");
                try
                {
                   response = await _client.PostAsync(apiUrl, content);
                }
                catch (Exception ex)
                {
                    if (attempt == retryCount)
                        _logger.TraceException($"DataServerClient Post failed", ex);
                }

                if (response != null && response.IsSuccessStatusCode)
                {
                    _logger.TraceInfo($"DataServerClient post was successful at retry count: {attempt}");
                    break;
                }

                backOff *= 2;
                await Task.Delay(backOff);
            }

            return (int)response.StatusCode;
        }

Can anyone provide clues for why this is failing or how I can gather diagnostics to find out what is happening? As I mentioned, the exception is not caught, the task that I create gets marked as completed, and no message gets posted.

Leon
  • 8,404
  • 2
  • 9
  • 52
David
  • 113
  • 1
  • 1
  • 7
  • I would suggest you add a try-catch to your HttpClient Wrapper, Secondly, I would suggest you read the output window thoroughly and look for clues. We at least need an exception to understand what's wrong otherwise all we would be doing is speculating!!! – FreakyAli Apr 28 '20 at 05:50
  • there is a try/catch around the _client.PostAsync call. It does not catch the problem though. – David Apr 29 '20 at 00:02
  • Please use foreground service to make a test. If you want to execute some get/post request in the background. https://learn.microsoft.com/en-us/xamarin/android/app-fundamentals/services/foreground-services . And JobService will not execute the task immediately. – Leon Apr 29 '20 at 06:09

0 Answers0