Forum Xamarin.Android

Async Task cannot be called in service without UI (invoked by broadcast)

I am developing an app to send the user location to the server on regular basis. The app should do the the job when the phone boot as well as the user start the app. It should be a popular use case.

I have a function to handle getting the current location and sending the location to the server. Since there are a few async tasks being called in the function, it is unavoidable that my function is asyn too.

After evaluated a few different approach with the use of broadcaset receiver for ActionBootCompleted, alarm manager, starting a service, or an intentservice, I ended up with the issue with my Async function that I cannot go any further.

Case 1: broadcast message ActionBootCompleted -> start service -> call my async function.

  • When it reach the point of calling the async function, the program terminate (run smoothly if the app is running with a UI).
  • I found that Task.Run() will not be executed in the scenario too, though no error will be occurred.

Case 2: UI -> start sticky service -> call my async function. App is terminated by the user manually -> sticky service restart -> call my async function

  • Similar to case 1, async function causes error and no Task.Run() can be executed.

It seems that no async / threading is allowed if the service is invoked by a broadcast message / sticky service restart without a UI.

I also found that async task is not allowed in an IntentService.

I have been stuck for weeks on this issue. Someone please give me some advice on how to call a async function in a service that is invoked without a UI. Any other suggestions to handle my use case will be appreciated.

Thank you very much.

Answers

Sign In or Register to comment.