Question

NOTE: All code below is based on a C#/Mono/Xamarin.Android.

I have a background service that at a certain point starts an activity and passes it a Handler, wrapped inside a Messenger:

intent.PutExtra("myHandler", new Messenger(handler));
context.StartActivity(intent);

When activity starts, I'd like to unwrap that Handler from intent and use it to send messages back to service when user does certain things, like click on a button. I tried the obvious:

override void OnCreate(Bundle bundle)
{
    ...

    myButton.Click += (s, e) => {
        var messenger = (Messenger)Intent.GetParcelableExtra("myHandler");
        var handler = (Handler)messenger.Binder; // This fails with invalid cast.

        handler.SendMessage(new Message() { What = MyButtonClicked });
    };
}

Debugger tells me that message.Binder is of type Handler, yet the cast fails. Google didn't find me anything helpful. I'm probably doing something very wrong, aren't I?

EDIT: OMG, I somehow managed to overlook the Messenger.Send() method. I should be using that to send messages to wrapped Handler, obviously!

Était-ce utile?

La solution

The proper way is to use messenger.Send() method.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top