.net MAUI Android call StartActivityForResult synchronously and wait OnActivityResult is called

264 Views Asked by At

from my application i need to create a new activity to an external app to retrieve a result in OnActivityResult . It's working well with StartActivityForResult then OnActivityResult is raised after externalActivity finished to process... So caller code is already finished...

So i would like to call the parent method in my viewModel which execute the StartActivityForResult code in an async / await context to have a business code linear without using a callback in the OnActivityResult...

Actually

public class MyViewModel
{
public async OnCallExternalIntent()
{
androidService.CreateExternalIntent() => this method calls inside StartActivityForResult then running thread is leaving and StartActivityForResult is raised. It's working....
}
}

But I would like to execute the method CreateExternalIntent in an await context to retrieve StartActivityForResult like that

public class MyViewModel
{
public async OnCallExternalIntent()
{
var otherActivityResult = await androidService.CreateExternalIntent();
}
}
public class MainActivity : MainApplication
{
    public Task CreateNewActivity()
    {
       StartActivityForResult(planeteMonetiqueIntent, transaction.InteropMessageId);
       AutoResetEvent.WaitOne();
       return Task.FromResult(_otherActivityResult);
    }
}

protected override void OnActivityResult(int requestCode, Result resultCode, Android.Content.Intent intent)
{
    Bundle bundle = intent.Extras;
    _otherActivityResult = GetDataFromBundle();
    AutoResetEvent.Set();
}

I did this process to synchronized with USB device to retrieve Arduino process and my caller code is working well with await...

I saw this topic Synchronous startActivityForResult - Waiting for Activity to Complete

I cannot use Instrumentation instrumentation = new Instrumentation(); instrumentation.AddMonitor(planeteMonetiqueIntentFilter, null, false);

instrumentation.StartActivitySync(planeteMonetiqueIntent);

this code raised an error, cannot execute this code in main thread....

I tired to explain my probleme as simple as I can...

THank you.

Julien

1

There are 1 best solutions below

0
Julien Duprat On

Use of autoREsetEvent at viewmodel level it is working