Xamarin Forms Android and dependency service run process

DustOfRust 141 Reputation points
2021-12-12T14:02:24.357+00:00

I want to run a process in Xamarin Forms on Android. I just don't know how much, nor have I found examples.

I only know that to be able to execute the code below I have to run it from the interface using dependency service.

I just don't know how to embed such a method in the code so that it works in the background and can send new results to UI, e.g. to Label

Below is a simple example of a method that performs the ping process.
I want to run using "Java.Lang.Runtime.GetRuntime (). Exec" because in the future I want to run other programs built into the Android system.

I am asking for any suggestions, possibly an example to be able to move on :)

public void ProcesStart()
{
 try
 {
 processIperf = Java.Lang.Runtime.GetRuntime().Exec("ping -c 100 1.1.1.1 ");
 Java.IO.BufferedReader bufferedReader = new Java.IO.BufferedReader(new Java.IO.InputStreamReader(processIperf.InputStream));
 while (true)
 {
 string processOutput = bufferedReader.ReadLine();
 if (processOutput == null)
 {
 break;
 }
 //How do I send results("processOutput ") to a Page or ViewModel?
 //So that when the user enters the page, he starts the process and gets the results.
 //And when it closes the application or go to another Page/ViewModel, the process will be killed.
 }
 }
 catch (Exception)
 {
 if (processIperf != null)
 processIperf.Destroy();
 processIperf = null;
 }
}

It's great if you give me an idea how to run this method in the background of another thread or Task? Surely it's important not to block the main thread?
Thanks for your help and suggestion :)

Developer technologies .NET Xamarin
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. JarvanZhang 23,971 Reputation points
    2021-12-13T09:55:19.867+00:00

    Hello @DustOfRust ,​

    Welcome to our Microsoft Q&A platform!

    I just don't know how to embed such a method in the code so that it works in the background and can send new results to UI, e.g. to Label

    Try using a service to perform the background process and keep it working, start the service on Android using DependencyService. Since Android 8.0, the service is limited in background. Please use a foreground service instead.

    After the process is finished, you could use MessagingCenter to send a message to let the contentPage to update the view.

    Best Regards,

    Jarvan Zhang


    If the response is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.