The proper way is to use messenger.Send()
method.
Retrieving Handler from Messenger after being parceled as Intent in Android
-
11-04-2022 - |
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!
La solution
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow