ildasm ildasm - 2 months ago 7
C# Question

Get value back from Handler

I have an embedded jar library in my app. In the OnCreate method I have to instantiate the library as seen in my code. There is no other way possible to use this library.
The Handler will be called and the result of the message is available, but there is no chance to bring the value ValueFromHandler back to the method OnCreate once it is available.
My Question is: Has anybody a small code snippet just to see how a handler should looks like which needs to return value back to caller?

This is my code:

public class MainActivity : Activity{
JarLibrary jarlib;

protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
jarlib = new JarLibrary(this, new JarHandler(), null);

jarlib.Run(ValueFromHandler) //Here I would need the value back from the handler

}}

public class JarHandler : Handler
{
public override void HandleMessage(Message msg)
{
switch (msg.What)
{
case jarlib.MessageStateChange:
if (msg.Arg1 == jarlib.StateReadyToRun)
{
ValueFromHandler = msg.Obj;
Console.WriteLine(ValueFromHandler); //Once this value "msg.Obj" is available I need to bring it back to the caller (On Create)
Toast.MakeText(Application.Context, "Ready to run", ToastLength.Short).Show();
}
break;
}
}
}

Answer

You could opt having a callback Action when you receive your message:

public class MainActivity : Activity
{
    JarLibrary jarlib;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);         
        SetContentView(Resource.Layout.Main);
        var handler = new JarHandler();
        jarlib = new JarLibrary(this, handler, null);

        handler.OnHandleMessage = (s, o) => {
            jarlib.Run(o);
        };
    }

    public class JarHandler : Handler
    {
        public Action<object> OnHandleMessage;

        public override void HandleMessage(Message msg)
        {
            switch (msg.What)
            {
                case jarlib.MessageStateChange:
                    if (msg.Arg1 == jarlib.StateReadyToRun)
                    {
                        OnHandleMessage?.Invoke(this, msg.Obj);

                        Console.WriteLine(ValueFromHandler); //Once this value "msg.Obj" is available I need to bring it back to the caller (On Create)
                        Toast.MakeText(Application.Context, "Ready to run", ToastLength.Short).Show();
                    }
                    break;
            }
        }
    }

You could also do it differently and pass in MainActivity in as argument in the constructor of your JarHandler class. Then set a property on MainActivity and then do something with that value.